MATLAB - 查找数组中的重复项并对其编号

MATLAB - Find and number duplicates within an array

我有一个值数组,其中一些值有重复,例如:

a = [5;5;4;7;7;3;3;9;5;7]

我想找出哪些是重复项,然后按顺序对每个进行编号,同时将非重复项设为零。例如:

b = [1;1;0;2;2;3;3;0;1;2]

目前我有一个非常低效和不完整的方法,使用unique函数和各种for循环和if语句,但觉得应该有一个简单的答案。

获得此答案的最有效方法是什么?

您可以结合使用 unique, accumarray, and ismember 进行必要的调整:

a = [5;5;4;7;7;3;3;9];

% Identify unique values and their counts
[uniquevals, ~, ia] = unique(a, 'stable');  % Stable keeps it in the same order
bincounts = accumarray(ia, 1);  % Count the frequency of each index in ia

% Zero out singles
singles = uniquevals(bincounts <= 1);
[~, singleidx] = intersect(a, singles);
a(singleidx) = 0;

% Overwrite repeats
repeats = uniquevals(bincounts > 1);
[~, a] = ismember(a, repeats);

其中 return 是新 a 的:

a =

     1     1     0     2     2     3     3     0

演练

我们在这里使用 unique 来查找输入数组 a 中的所有唯一值。我们还存储了可选的第三个输出,它是 a 的值到唯一值数组中它们的索引的映射。请注意,我们正在使用 stable 选项按照它们在 a 中首次遇到的顺序获取唯一值; unique 的结果默认排序。

然后我们使用accumarray累加我们从unique得到的下标,这给了我们每个索引的计数。使用 logical indexing,我们首先使用这些计数将单个实例清零。将这些归零后,我们可以滥用使用ismember的第二个输出来return最终答案。

这是一个基于索引、逻辑运算符和cumsum的解决方案:

x = [false; a(2:end)==a(1:end-1)]; %logical indexes of repeated elements except the first element of each block 
y = [x(2:end)|x(1:end-1) ;x(end)]; %logical indexes of repeated elements
result = cumsum(~x&y).*y           %cumsum(...):number all elements sequentially and (... .* y): making non-duplicates zero

编辑:

随着问题的编辑,要处理不连续的重复项,您可以这样做:

[s ii] = sort(a);
x = [false ;s(2:end)==s(1:end-1)];
y = [x(2:end)|x(1:end-1) ;x(end)];
first = ~x&y;
[~,ix]=sort(ii(first));
un(ix,1)=1:numel(ix);
result(ii,1)=un(cumsum(first)).*y;

这是一个双衬纸,也适用于非连续重复

[c, ia, ic] = unique(a, 'stable');
[~, b] = ismember(a, a(ia(accumarray(ic,1)>1)));

我使用了 中的一些想法并进行了修改。

这是另一种方法:

a = [5;5;4;7;7;3;3;9;5;7];
[u, ~, w] = unique(a, 'stable');
s = find(sum(bsxfun(@eq, a, u.'), 1) > 1);
b = sum(bsxfun(@times, bsxfun(@eq, w, s), 1:numel(s)), 2);

从 R2016b 开始,您可以简化语法:

a = [5;5;4;7;7;3;3;9;5;7];
[u, ~, w] = unique(a, 'stable');
s = find(sum(a==u.', 1) > 1);
b = sum((w==s).*(1:numel(s)), 2);