是否可以在 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
提供的索引?
最佳答案
以下代码首先计算每个元素出现的频率,然后使用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
的定义复制自 this answer :
对于 MATLAB R2015a+:
function V = runLengthDecode(runLengths, values)
if nargin<2
values = 1:numel(runLengths);
end
V = repelem(values, runLengths);
end
对于 R2015a 之前的版本:
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
关于arrays - 按元素出现的频率对数组元素进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31671518/