Michael L.
Michael L.

Reputation: 473

how to find the order of elements in array in Matlab?

If I have an array of A = [10 1 5 20] I want a program to find indexes of the elements. In this case Idx = [3 1 2 4]. I am using [~,Idx]=sort([10 1 5 20]) and get the following:

Idx =
        
    2     3     1     4

It's totally not what I expected. I even don't understand how the program got those numbers.

Upvotes: 1

Views: 438

Answers (1)

OmG
OmG

Reputation: 18838

It is simple:

A = [10 1 5 20];
[~, Idx] = sort(A);
[~, orders] = sort(Idx);

% orders
% [3 1 2 4]

orders is your answer. You need to get the indices of sorted Idx.

Note that Idx(i) represents the index of i-th element in the original array A.

Upvotes: 3

Related Questions