Pugl
Pugl

Reputation: 452

Order an array according to another array in MATLAB

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

Upvotes: 0

Views: 64

Answers (1)

beaker
beaker

Reputation: 16791

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

Upvotes: 4

Related Questions