replacing different elements in a matrix according to different conditions
2 views (last 30 days)
Show older comments
MiauMiau
on 11 May 2015
Commented: Image Analyst
on 12 May 2015
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 Comments
Image Analyst
on 12 May 2015
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.
Accepted Answer
Sebastian Castro
on 11 May 2015
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 Comments
Joseph Cheng
on 11 May 2015
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.)
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!