Sort in matlab and assign ranking

Hi, I need to sort a vector and assign a ranking for the appropriate sort order. I use the sort function [sortedValue_X , X_Ranked] = sort(X,'descend'); but the problem is that it assigns different ranks for the same values ​​(zeros). those. x = [ 13 15 5 5 0 0 0 1 0 3] , and I want the zeros to have the same last rating, which is 6, and the fifth should share the third class, etc. any suggestions?

+4
source share
2 answers

The syntax [sortedValues, sortedIndexes] = sort(x, 'descend') does not return the rank as you describe it. It returns indexes of sorted values. This is really useful if you want to use the sort order from one array to change another array.

As suggested by @ user1860611, unique seems to do what you want using the third output as follows:

 x = [ 13 15 5 5 0 0 0 1 0 3]; [~, ~, forwardRank] = unique(x); %Returns %forwardRank = % 5 6 4 4 1 1 1 2 1 3 

To get the order you need (decending), you will need to cancel the order, for example:

 reverseRank = max(forwardRank) - forwardRank + 1 %Returns %reverseRank = % 2 1 3 3 6 6 6 5 6 4 

You can do it at this moment. But you can sort them in descending order. This is a reordering of the reverseRank vector, which keeps it in sync with the original vector x , which is exactly what you need for the 2nd argument to sort . Therefore, we can do something like this:

 [xSorted, ixsSort] = sort(x, 'descend'); %Perform a sort on x reverseRankSorted = reverseRank(ixsSort); %Apply that sort to reverseRank 

What generates:

 xSorted = 15 13 5 5 3 1 0 0 0 0 reverseRankSorted = 1 2 3 3 4 5 6 6 6 6 
+10
source

tiedrank.m may be what you are looking for.

 >> x = round(rand(1,5)*10) x = 8 7 3 10 0 >> tiedrank(x) ans = 4 3 2 5 1 
+5
source

All Articles