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
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
Sebastian Castro 2015-5-11
You can use logical indexing to find elements in a matrix that correspond to a certain value.
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
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 CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by