1
M1 = 

     1   --> Position 1
     2   --> Position 2
     1   --> Position 3
     2   --> Position 4

M2 =

     2     1     3     4

I need help in coding for a simple program. I have two matrices (or arrays, samples given above) and I want to update M2 according to M1.

For instance, whatever number is present in M1 third position gets updated in every index of M2 where number 3 is present. And the same goes for all positions of M2.

So, my desired result would be like this: M2 = [2 1 1 2]

How can I accomplish this?

2
  • 1
    in.mathworks.com/matlabcentral/answers/… Commented Jan 30, 2018 at 13:32
  • @Hazem : Thanks..but this isn't what i have mentioned. i want to replace the numbers in M2 according to M1, not sort them. Commented Jan 30, 2018 at 14:11

2 Answers 2

2

This can be done with a simple indexing operation:

M2 = M1(M2);
Sign up to request clarification or add additional context in comments.

1 Comment

@GavanpreetSingh: Happy to help. Don't forget that you can mark answers as accepted.
0

You could try something like

for i = 1:length(M1)
    M2(M2 == i) = M1(i);
end

M2 == i uses the logic equality operator ==, and it returns a vector of the same size of M2 with ones in the positions where the elements are equal to i and zeros otherwise. So for example if M2 = [1 2 2 3], M2 == 2 would return [0 1 1 0].

Using this vector as the index argument select only the elements where the indexing vector is 1. Following the previous example M2(M2 == 2) is equal to M2([0 1 1 0]) and will select the second and third elements, which are the ones that are equal to 2.

If we now put it in a loop and iterate over all positions of M1, M2(M2 == i) selects all elements in M2 that match M2 == i and you want to assign the value M1(i) to those elements.

2 Comments

It is working perfectly fine...but i haven't understand how. Maybe you can explain a little bit if it doesn't bother you...Many thanks for code, anyway....
I tried to explain how it works. I hope that's better :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.