计算数组中的重复整数 [英] Count repeating integers in an array

查看:81
本文介绍了计算数组中的重复整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这个向量:

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已排序,这是使用 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

这篇关于计算数组中的重复整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆