replacing different elements in a matrix according to different conditions

5 visualizzazioni (ultimi 30 giorni)
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 Commenti
MiauMiau
MiauMiau il 11 Mag 2015
you are right, that is the fastest possibility indeed! thanks!
Image Analyst
Image Analyst il 12 Mag 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.

Accedi per commentare.

Risposta accettata

Sebastian Castro
Sebastian Castro il 11 Mag 2015
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 Commenti
Joseph Cheng
Joseph Cheng il 11 Mag 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.)

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by