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

Arrays 按数组元素的频率对数组元素进行排序,arrays,matlab,sorting,octave,Arrays,Matlab,Sorting,Octave,在matlab/octave中,是否可以使用sort函数根据数组元素的相对频率对数组进行排序 例如数组 m= [4,4,4,10,10,10,4,4,5] 应生成此数组: [5,10,10,10,4,4,4,4,4] 5是频率较低的元素,位于顶部,而4是频率最高的元素,位于底部。 如果要使用histcount提供的索引,一种方法是使用accumarray查找每个数字的计数(我怀疑您可以使用histcounts(m,max(m))),但您必须清除所有0s) 通过将我的方法与您的方法相结合,可

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

例如数组

m= [4,4,4,10,10,10,4,4,5]
应生成此数组:

[5,10,10,10,4,4,4,4,4]
5
是频率较低的元素,位于顶部,而
4
是频率最高的元素,位于底部。
如果要使用
histcount
提供的索引,一种方法是使用
accumarray
查找每个数字的计数(我怀疑您可以使用
histcounts(m,max(m))
),但您必须清除所有
0
s)


通过将我的方法与您的方法相结合,可以得到一个更简单的解决方案:

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)

下面的代码首先计算每个元素出现的频率,然后使用
runLengthDecode
展开唯一的元素

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

u_m = unique(m);

elem_count = histc(m,u_m);
[elem_count, idx] = sort(elem_count);

m_sorted = runLengthDecode(elem_count, u_m(idx));

runLengthDecode
的定义复制自:

对于MATLAB R2015a+:

function V = runLengthDecode(runLengths, values)
if nargin<2
    values = 1:numel(runLengths);
end
V = repelem(values, runLengths);
end

您可以使用、that计算重复次数,并将排序应用于
m

[~, ind] = sort(sum(bsxfun(@eq,m,m.')));
result = m(ind);

除了您已有的链接之外,您还应该在回答中发布
runlegnthDecode
的实际代码。。。还要注意的是,
repelem
是一个非常新的函数,因此它在旧版本的Matlab上不起作用(不过,使它起作用并不困难)。虽然通过组合我们的两个答案,您可以通过使用排序避免使用
runlengthDecode
。@Dan我从原始答案复制了代码;它不一定依赖于
repelem
function V = runLengthDecode(runLengths, values)
%// Actual computation using column vectors
V = cumsum(accumarray(cumsum([1; runLengths(:)]), 1));
V = V(1:end-1);
%// In case of second argument
if nargin>1
    V = reshape(values(V),[],1);
end
%// If original was a row vector, transpose
if size(runLengths,2)>1
    V = V.'; %'
end
end
[~, ind] = sort(sum(bsxfun(@eq,m,m.')));
result = m(ind);