使用Matlab查找并索引数组中的重复元素

时间:2014-06-06 07:27:53

标签: arrays matlab

我有一个数组A = [10 20 20 30 40 10 50];

是否有任何智能方法可以找到并找到此数组的重复元素?

即。

10: [1 6]; 
20: [2 3];

我尝试使用unique,但我失败了......

4 个答案:

答案 0 :(得分:2)

这是一个解决方案:

% 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

答案 1 :(得分:1)

这是另一个:

>> 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

答案 2 :(得分:1)

bsxfunarrayfun

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

答案 3 :(得分:0)

此解决方案仅返回值而不是值的索引(位置)。

%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));