[英]Find and indexing repeating elemnts in an array using Matlab
我有一个数组A = [10 20 20 30 40 10 50];
有什么聪明的方法来查找和定位此数组的重复元素吗?
即
10: [1 6];
20: [2 3];
我尝试使用unique
身份,但失败了...
这是一种解决方案:
% input array
A = [10 20 20 30 40 10 50];
% find unique elements (vals), and map values of A to indices (valsIdx)
[vals,~,valsIdx] = unique(A);
% group element locations by the above indices mapping
locs = accumarray(valsIdx, 1:numel(valsIdx), [], @(x){sort(x)});
% keep only values that are repeated
idx = cellfun(@numel, locs) > 1;
vals = vals(idx);
locs = locs(idx);
结果:
vals =
10 20
locs =
[2x1 double]
[2x1 double]
>> celldisp(locs)
locs{1} =
1
6
locs{2} =
2
3
这是另一个:
>> A = [10 20 20 30 40 10 50];
>> S = sort(A);
>> S = arrayfun(@(x) [x find(x==A)], unique(S(diff(S)==0)), 'UniformOutput', false);
>> S{:}
ans =
10 1 6
ans =
20 2 3
如果您没有或不想使用arrayfun
,则可以使用普通循环:
A = [10 20 20 20 30 40 10 50];
S = sort(A);
S = unique(S(diff(S)==0));
R = cell(size(S'));
for ii = 1:numel(S)
R{ii} = [S(ii) find(A==S(ii))]; end
使用bsxfun
和arrayfun
:
comp = tril(bsxfun(@eq, A(:), A(:).')); %'// compare all pairs of values
ind = find(sum(comp)>1); %// find repeated values
values = A(ind);
positions = arrayfun(@(n) find(comp(:,n).'.*(1:numel(A))), ind, 'uni', 0);
这给出:
>> values
values =
10 20
>> positions{:}
ans =
1 6
ans =
2 3
此解决方案仅返回值,而不返回值的索引(位置)。
%Your Data
A=[10 20 20 30 40 10 50];
%sorted Data
A_sorted=sort(A);
%find the duplicates
idx=find(diff(A_sorted)==0);
% the unique is needed when there are more than two duplicates.
result=unique(A_sorted(idx));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.