给向量中的数字分配等级 [英] Assign rank to numbers in a vector

查看:110
本文介绍了给向量中的数字分配等级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够根据向量的大小为数字分配一个等级,并创建一个包含这些等级的新向量.

I want to be able to assign a rank to numbers in a vector depending on their size and make a new vector containing these ranks.

例如,如果我有向量[5, 2, 3, 1],我想返回[4, 2, 3, 1](因为5是最大的数字而1是最小的数字).相等的数字最好共享一个平均等级(例如,如果两者相同并且是最低的,则它们的平均等级应该为1.5).

For instance, if I have the vector [5, 2, 3, 1], I want to return [4, 2, 3, 1] (as 5 is the largest number and 1 is the smallest). Equal numbers should share an average rank preferably (for instance, if both are the same and are the lowest, they should get an average rank of 1.5).

如何在MATLAB中实现这一目标?

How can I achieve this in MATLAB?

推荐答案

建议您使用unique:

[~, ~, ranking] = unique(x);

它也对向量进行排序,但是将相同的值映射到相同的索引.这样,原始向量中的相同元素将获得相同的排名.例如,如果x = [5 2 3 1 3],我们得到:

It also sorts the vector but maps identical values to the same index. This way identical elements in the original vector get the same rank. For instance, if x = [5 2 3 1 3], we get:

ranking =
   4   2   3   1   3

如果您希望获得平均"排名,则可以将accumarray与从uniquesort获得的信息结合使用,因此请执行以下操作:

If you want an "average" rank, you could use accumarray in combination with the information obtained both from unique and from sort, so do the following instead:

[~, ~, idx_u] = unique(x);
[~, idx_s] = sort(x);
mean_ranks = accumarray(idx_u(:), idx_s(idx_s), [], @mean);
ranking = mean_ranks(idx_u);

在我们的示例中,我们将得到:

In our example we would get:

ranking =
   1.0000
   2.0000
   3.5000
   5.0000
   3.5000

请注意,这两个值3的平均排名均为3.5,因为它们的排名分别为3和4.

Note that both values 3 got the average rank of 3.5, as they shared ranks 3 and 4.

这篇关于给向量中的数字分配等级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆