在matlab中排序并分配排名 [英] sort in matlab and assign ranking
问题描述
我需要对向量进行排序,并为相应的排序顺序分配等级.我正在使用排序功能[sortedValue_X , X_Ranked] = sort(X,'descend');
但问题是它为相同的值(零)分配了不同的等级.
即x = [ 13 15 5 5 0 0 0 1 0 3]
,我希望0占据最后一个相同的排名,即6,而5则需要共享第3排名,依此类推.
有什么建议吗?
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?
推荐答案
语法[sortedValues, sortedIndexes] = sort(x, 'descend')
不会像您所描述的那样返回等级.它返回排序后的值的索引.如果要使用一个数组的排序顺序来重新排列另一个数组,这将非常有用.
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.
如@ user1860611所建议,unique
似乎可以使用第三个输出,如您所愿:
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
此时您可能已经完成.但是您可能希望将它们按升序排列.这是reverseRank
向量的重新排序,可使其与原始x
向量保持同步,这正是sort
的第二个参数所希望提供的帮助.所以我们可以做这样的事情:
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
哪个生成:
xSorted = 15 13 5 5 3 1 0 0 0 0
reverseRankSorted = 1 2 3 3 4 5 6 6 6 6
这篇关于在matlab中排序并分配排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!