replacing different elements in a matrix according to different conditions

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 comentarios

... and 1 would not change?
What do you do with 1's
you are right, so it would be
5 -> 0
4 -> 1
3 -> 2
2 -> 3
1 -> 4
5 -> 0
Based on those rules, you could "cheat" and do this completely without logic:
out = 5 - in
you are right, that is the fastest possibility indeed! thanks!
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.

Iniciar sesión para comentar.

 Respuesta aceptada

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 comentarios

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.)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 11 de Mayo de 2015

Comentada:

el 12 de Mayo de 2015

Community Treasure Hunt

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

Start Hunting!

Translated by