Q&A
Ask and answer questions to make information more available to wider audiences.
Aidan Mound @aidanmound   18, Aug 2023 12:00 AM
Find elements from A in B and get the index of the found element in B
I have two arrays, A and B. Find every instance when an element in A equals B and get the index of B when this occurs.

A = [4 4 8 9 7 2 32 5 45 98 7 1 3 3 3]
B = [4 8 9 8 7 7 5 12 32 56 74 12 75 2 7 4]

answers 1
 
Answer 1
Cesar Borne @bornecesar   30, Aug 2023 05:30 PM
Consider that elements of A might occur once, others multiple times, and some not at all. Therefore we need to resort to cell arrays and then with arrayfun, you can loop over all elements of A to find the coincidences and store them in C.

C = arrayfun(@(x) find(B==x), A, 'un', 0)
Now C{k} holds the indices into B, where B equals A(k). For example, A(1) = 4 and C{1} = 1 16, i.e., B(1) and B(16) are equal to 4.