Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

sorting - sort in matlab and assign ranking

Hi I need to sort a vector and assign a ranking for the corresponding sorting order. I'm using sort function [sortedValue_X , X_Ranked] = sort(X,'descend'); but the problem is it assigns different ranks for the same values (zeros). i.e. x = [ 13 15 5 5 0 0 0 1 0 3] and I want zeros to take the same last rank which is 6 and fives needs to share the 3rd rank etc.. any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The syntax [sortedValues, sortedIndexes] = sort(x, 'descend') does not return rank as you describe it. It returns the indexes of the sorted values. This is really useful if you want to use the sort order from one array to rearrange 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 want (decending) you'll need to reverse the order, like this:

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

You may be done at this point. But you may want to sort these into the into an acsending order. This is a reorder of the reverseRank vector which keeping it in sync with the original x vector, which is exactly what the 2nd argument of sort is desined to help with. So we can do something like this:

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

Which generates:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...