MATLAB: Obtaining the rank ordering of a vector, with no tied ranks allowed

I've got a vector A = [6 5 7 7 4] and want to obtain the ranks as either [3 2 4 5 1] or [3 2 5 4 1] - I don't mind which. The answer is a vector in which each element is replaced by the rank it holds. This indicates to me that the fifth element is the smallest, then the second element is the second smallest, and so on.

I thought of doing [~,~,rnk] = unique(A), however that doesn't work, and produces instead [3 2 4 4 1].

How can I obtain the solution with no tied ranks?

Upvotes: 0

Views: 103

Answers (1)

Jørgen
Jørgen

Reputation: 863

It's almost a duplicate of this question.

We use sort twice, first sorting the array to get the index and then sort the index.

A = [6 5 7 7 4];
[~, rnk] = sort(A);
[~, rnk] = sort(rnk);
rnk =

     3     2     4     5     1

Upvotes: 3

Related Questions