如果我有这个向量:
x = [1 1 1 1 1 2 2 2 3 4 4 6 6 6 6]
我想根据自己得到每个唯一数字的位置。
y = [1 2 3 4 5 1 2 3 1 1 2 1 2 3 4]
目前我正在使用:
y = sum(triu(x==x.')) % MATLAB 2016b and above
它很紧凑,但显然内存效率不高。
为了 MATLAB 编程的纯粹美感,我会避免使用循环。你有更好的简单实现吗?
上下文:
我的最终目标是对向量 x
进行排序,但限制条件是出现 N
次的数字优先于出现次数超过 的另一个数字>N
次:
[~,ind] = sort(y);
x_relative_sort = x(ind);
% x_relative_sort = 1 2 3 4 6 1 2 4 6 1 2 6 1 6 1
最佳答案
假设 x
已排序,这是一个使用 unique
的矢量化替代方案, diff
, 和 cumsum
:
[~, index] = unique(x);
y = ones(size(x));
y(index(2:end)) = y(index(2:end))-diff(index).';
y = cumsum(y);
现在您可以应用最终排序:
>> [~, ind] = sort(y);
>> x_relative_sort = x(ind)
x_relative_sort =
1 2 3 4 6 1 2 4 6 1 2 6 1 6 1
关于matlab - 计算数组中的重复整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54079558/