0

Given I have two arrays, say:

a = [0.8, 0.2,0.1,20,1.5,5.8,12]

b = [2,1,3,1,2,2,3]

Now I want to order the entries in a according to the numbers in b, in that I would want to have all 1's first in the respective order, then the 2s, then the 3.., for these example arrays I would want to get the following:

c = [0.2,20,0.8,1.5,5.8,0.1,12]

How can I do that efficiently in MATLAB? Tks

1 Answer 1

4

First, sort b and get the indices of b in the sorted matrix (the second output of sort). Since this is a stable sort, order will be preserved. Then use those indices in a to get the resulting array:

>> a = [0.8, 0.2,0.1,20,1.5,5.8,12];
>> b = [2,1,3,1,2,2,3];
>> [~,I]=sort(b)
I =

   2   4   1   5   6   3   7

>> a(I)
ans =

    0.20000   20.00000    0.80000    1.50000    5.80000    0.10000   12.00000
Sign up to request clarification or add additional context in comments.

1 Comment

ah I didn't know that you can get the indices from the original matrix with sort, thanks!!

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.