How to quickly find out the repeat integers in an array?
Show older comments
Dear All,
I have an array A which contains repeat intergers (entries). For example, A = [4 20 5 4 7 5 9 5 31]. I want to find out the repeat elements {4, 5} and their locations.
Thanks.
Benson
Accepted Answer
More Answers (1)
A = [4 20 5 4 7 5 9 5 31]
mA = min(A(:)) - 1;
At = A(:) - mA;
locs = accumarray(At, (1:length(At)), [], @(V) {V.'});
dups = cellfun(@length,locs) > 1;
info = [num2cell(At(dups)+mA), locs(dups)]
... but most people might find that too obscure. Less obscure might be
[G, uA] = findgroups(A);
info = cell(0,2);
for K = 1 : max(G)
matches = find(G == K);
if length(matches) > 1
info(end+1,:) = {uA(K), matches};
end
end
info
1 Comment
Benson Gou
on 4 Jun 2021
Categories
Find more on Dates and Time in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!