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?
source share