且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按数组元素的频率对数组元素进行排序

更新时间:2022-01-25 22:48:58

一种方法是使用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)