arrays - 按元素出现的频率对数组元素进行排序

标签 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 提供的索引?

最佳答案

以下代码首先计算每个元素出现的频率,然后使用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/

相关文章:

java - 如何读取数组的方法?在java中

java - 使用长度为零的数组

arrays - 用缺失数字的新 1 元素数组填充二维数组(来自初始的子数组)

arrays - 使用 accumarray 和用户定义函数返回第三列值的 Octave 组统计计算

c++ - 试图仅在 C++ 中模拟 Matlab "unique"函数

python - 这些元组可以以某种方式排列吗?

java - 排序并消除重复项

javascript - 从对象数组中过滤一些对象

带有 'rows' 和索引的 ismember 的 Python 版本

python - python中对一列数据进行排序需要分组