如果我有这个向量:
x = [1 1 1 1 1 2 2 2 3 4 4 6 6 6 6]我想根据自己的位置获取每个唯一编号的位置.
I would like to get the position of each unique number according to itself.
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它很紧凑,但内存效率显然不高.
It's compact but obviously not memory efficient.
为了使MATLAB编程具有纯粹的美感,我将避免使用循环.您是否有更好的简单实现?
For the pure beauty of MATLAB programming I would avoid using a loop. Do you have a better simple implementation ?
上下文:
我的最终目标是对向量x进行排序,但受到一个约束,即出现次数N的数字要优先于出现次数超过N的另一个数字:
My final goal is to sort the vector x but with the constraint that a number that appear N times has the priority over another number that has appeared more than N times:
[~,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 :
Assuming x is sorted, here's one vectorized alternative using unique, diff, and cumsum:
[~, index] = unique(x); y = ones(size(x)); y(index(2:end)) = y(index(2:end))-diff(index).'; y = cumsum(y);现在您可以应用最终排序:
And now you can apply your final sorting:
>> [~, 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更多推荐
计算数组中的重复整数
发布评论