Matlab rank values ​​in a vector with repeating elements multiple times

I would like to rank (arrange) the elements of a vector in Matlab and elements with the same value have the same rank (in descending order). Therefore, I need a procedure such as:

>> Rank = ComputeRanking([ 5 10 5 5 1]) Rank = 2 1 2 2 5 

I found a partial solution on the mathworks website: ranking values :

 function vecRank = ComputeRanking2(dataVector) % % Sort data in descending order with duplicates % [srt, idxSrt] = sort(dataVector,'descend'); % Find where are the repetitions idxRepeat = [false; diff(srt) == 0]; % Rank with tieds but w/o skipping rnkNoSkip = cumsum(~idxRepeat); % Preallocate rank vecRank = 1:numel(dataVector); % Adjust for tieds (and skip) vecRank (idxRepeat) = rnkNoSkip(idxRepeat); % Sort back vecRank (idxSrt) = vecRank ; end 

This works if there is one duplicate (2 elements with the same value), but if there are 2 or more of them, as in my example, this does not work. How to do to handle an arbitrary number of duplicates?

+5
source share
2 answers

unique with 'stable' makes this easy:

 [srt, idxSrt] = sort(dataVector,'descend'); [~,rnk,idxrnk] = unique(srt, 'stable'); unsorted = rnk(idxrnk); result = unsorted(idxSrt)' 
+8
source

Here's another way: the rank of each element is 1 plus the number of unique elements that are less than that element:

 result = 1 + sum(bsxfun(@lt, dataVector(:).', dataVector(:)), 1); 

In the case of dataVector = [5 10 5 5 1]; this gives

 result = 2 1 2 2 5 
+5
source

Source: https://habr.com/ru/post/1235688/


All Articles