replacing different elements in a matrix according to different conditions
2 ビュー (過去 30 日間)
古いコメントを表示
Hi
I have an array which contains integers from 0 to 5. Now I want to replace all 5s with a 0, all 0 with a 5, the 2s with a 4 and vice versa and the 3 would not be changed. I know that I could do that with several nested if loops - but is there a faster/smarter way?
6 件のコメント
Image Analyst
2015 年 5 月 12 日
There is a general function that lets you map any integer into any other number you want in a single line of code. It's general, not just "5-in" which coincidentally happens to work for this particular case. However based on your request - the only one I've ever gotten on over 15,000 questions answered - I won't answer.
採用された回答
Sebastian Castro
2015 年 5 月 11 日
For instance, let's the take the logical test that a value is equal to 5. For some value x , you know you can enter the expression below and get a true-false response.
x == 5
In MATLAB, you can also do this for an entire matrix M . I've created a random matrix as follows:
M = randi(6,[10 10]) - 1
The following line will return a matrix the same size as M whose elements are 0 or 1 depending on the above condition (is equal to 5). Try it out for yourself on such a matrix.
M == 5
So, if you want to replace all those elements with a zero, use the logical indices and assign those to a value of 0:
M(M==5) = 0
- Sebastian
2 件のコメント
Joseph Cheng
2015 年 5 月 11 日
If you go sebastian's route then you'd want to make sure you index each condition before you start swapping.
for ind = unique(M)
swapele(ind,:) = M== ind;
end
then go through a for loop to swap out (probably a switch statement would be best.)
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!