按数组元素的频率对数组元素进行排序 [英] Sort array elements by the frequency of its elements

查看:167
本文介绍了按数组元素的频率对数组元素进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在matlab/octave中是否可以使用sort函数根据其元素的相对频率对数组进行排序?

Is it possible in matlab/octave to use the sort function to sort an array based on the relative frequency of their elements?

例如数组

m= [4,4,4,10,10,10,4,4,5]

应生成以下数组:

[5,10,10,10,4,4,4,4,4]

5是频率较低的元素,位于顶部,而4是频率最高的元素,位于底部. 应该使用histcount提供的索引吗?

5 is the less frequent element and is on the top while 4 is the most frequent and it's on bottom. Should one use the indices provided by histcount?

推荐答案

一种方法是使用accumarray查找每个数字的计数(我怀疑您可以使用histcounts(m,max(m))),但是您必须清除所有0 s).

One way would be to use accumarray to find the count of each number (I suspect you can use histcounts(m,max(m))) but then you have to clear all the 0s).

m = [4,4,4,10,10,10,4,4,5];

[~,~,subs]=unique(m);
freq = accumarray(subs,subs,[],@numel);
[~,i2] = sort(freq(subs),'descend');

m(i2)


通过将我的方法与 m.s. 结合起来,可以获得更简单的解决方案:


By combinging my approach with that of m.s. you can get a simpler solution:

m = [4,4,4,10,10,10,4,4,5];

[U,~,i1]=unique(m);
freq= histc(m,U);
[~,i2] = sort(freq(i1),'descend');

m(i2)

这篇关于按数组元素的频率对数组元素进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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