[英]Find and indexing repeating elemnts in an array using Matlab
I have an array A = [10 20 20 30 40 10 50];
我有一个数组
A = [10 20 20 30 40 10 50];
Is there any smart way to find and locate the repeating elements of this array ? 有什么聪明的方法来查找和定位此数组的重复元素吗?
ie 即
10: [1 6];
20: [2 3];
I tried to use unique
but I failed ... 我尝试使用
unique
身份,但失败了...
Here is one solution: 这是一种解决方案:
% 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);
The result: 结果:
vals =
10 20
locs =
[2x1 double]
[2x1 double]
>> celldisp(locs)
locs{1} =
1
6
locs{2} =
2
3
Here is another: 这是另一个:
>> 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
If you don't have or want to use arrayfun
, you can use a plain loop: 如果您没有或不想使用
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
With bsxfun
and arrayfun
: 使用
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);
This gives: 这给出:
>> values
values =
10 20
>> positions{:}
ans =
1 6
ans =
2 3
This solution only returns the values not the indices(location) of the values. 此解决方案仅返回值,而不返回值的索引(位置)。
%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.