# Vectorized alterlative to identify duplicate elements in an array

2 visualizzazioni (ultimi 30 giorni)
fsgeek il 6 Mar 2020
Commentato: fsgeek il 6 Mar 2020
Hello everyone,
I have a 1xN array, A, of random integers. Repetitions are permitted. Let's consider only the integers 1:5 to make things simple:
A = [1, 5, 3, 4, 4, 2, 3, 1, 4, 5, 3, 2, 3, 4, 2, 3];
I generate a second 1xN array, B, which represents an arbitrary subset of unique(A):
B = [1, 3, 4];
For each element in B, I would like to find all of the corresponding indexes in A. So far I am using a simple FOR loop to achieve this:
indexes = [];
for i = 1:length(B)
indexes = [indexes, find(A == B(i))];
end
I would like to write an alternative which does not require a FOR loop. My problem is that for each element in B, I want all of the corresponding indexes in A. Functions like ISMEMBER and INTERSECT do not include repetitions.
I don't need to distinguish between the elements in B, so the output can be a single 1xN vector containing all of the indexes in A. For the above example, the output would be:
indexes = [1, 8, 3, 7, 11, 13, 16, 4, 5, 9, 14];
The final order of INDEXES is arbitrary. It can be sorted or random.
Thanks!
EDIT: I found the solution:
[LIA, ~] = ismember(A, B);
indexes = find(A(LIA));
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

fsgeek il 6 Mar 2020
Modificato: fsgeek il 6 Mar 2020
[LIA, ~] = ismember(A, B);
indexes = find(LIA);
##### 2 CommentiMostra NessunoNascondi Nessuno
Stephen23 il 6 Mar 2020
Modificato: Stephen23 il 6 Mar 2020
Simpler on one line:
>> indices = find(ismember(A,B))
indices =
1 3 4 5 7 8 9 11 13 14 16
fsgeek il 6 Mar 2020
Looks good, thanks for the tip!

Accedi per commentare.

### Più risposte (1)

Jakob B. Nielsen il 6 Mar 2020
Logical indexing for every instance, then convert the logical output to doubles and sum it (since you cant sum logicals), and find the indexes where there is a 1, at a glance. It wont give the same order of indexes as in your example but I guess that doesnt matter too much if you dont need to distinguish the elements in B.
logic=(A==B(:));
logic=sum(double(logic));
find(logic==1)
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Logical in Help Center e File Exchange

R2014a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by