Ranking vectors from highest to lowest including repeated ranks.

9 views (last 30 days)
If I have a vector say [0.4 0.1 0.1 0.2 0.1 0.05 0.05], then I want to rank this vector with output [1 3 3 2 3 6 6] (i.e. ranking number in the usual way)
Currently I'm using
X = [0.4 0.1 0.1 0.2 0.1 0.05 0.05]
Rnk = floor(tiedrank(-X));
This outputs:
Rnk = [1 4 4 2 4 6 6]
But this doesn't work because I want the third ranked element to output 3 in each case, but tiedrank function is computing the mean(3,4,5) = 4. This method does work when there are only 2 repeats because, for example, for the 0.05 elements, they should be rank 6, but tiedrank function computes mean(6,7)=6.5 and floor(6.5) = 6, and my vectors usually have several entries that are similar:
For example let
X = [0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 ]
Rnk = floor(tiedrank(-X));
returns
Rnk = [5 5 5 5 5 5 5 5 5 5]
instead of [1 1 1 1 1 1 1 1 1 1 1] since the function computes mean(1,2,3,4,5,6,7,8,9,10) = 5.5 and floor(5.5) = 5. Is there a simple function that can yield me my desired output?

Accepted Answer

Cameron
Cameron on 9 Mar 2023
I'm not sure how you want your ranking to occur. Why would your output be [1 3 3 2 3 6 6] instead of [1 3 3 2 3 4 4]? Either way, this is how I would do it.
X = [0.4 0.1 0.1 0.2 0.1 0.05 0.05];
[~,~,Rnk] = unique(-X)
Rnk = 7×1
1 3 3 2 3 4 4
  2 Comments
William
William on 9 Mar 2023
Hi, Is there a way to make this work to show 6 instead of 4? It's because if you imagine a race in which there's and there's a tie for 2nd place, then the fourth person isn't 3rd, he's 4th? (Assume there's only 1 winner)
Cameron
Cameron on 9 Mar 2023
I understand. In this case, I would do this
X = [0.4 0.1 0.1 0.2 0.1 0.05 0.05];
X_sorted = sort(-X);
[~,Rnk] = ismember(-X,X_sorted)
Rnk = 1×7
1 3 3 2 3 6 6

Sign in to comment.

More Answers (1)

Marco Riani
Marco Riani on 9 Mar 2023
Hi William, I did it using a loop. Please let me know if the code below is what you wanted
x=[0.4 0.1 0.1 0.2 0.1 0.05 0.05];
out=zeros(size(x));
for j=1:length(x)
if max(x)>-Inf
sel=x==max(x);
out(sel)=sum(out>0)+1;
x(sel)=-Inf;
end
end
disp('Ranking')
Ranking
disp(out)
1 3 3 2 3 6 6

Categories

Find more on Mathematics in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!