MATLAB: Find elements from A in B and get the index of found element in B

arrayfindmatrix array

Hi
I have two arrays, A and B, A has 12,000 elements and B has 260,000 elements.
I need to find every instance when an element in A equals B and get the index of B when this occurs.
So for example at A(5) I need to search all elements of B for the value in A(5) and return the index location of B where it is found.
var_found = []
for i : length(A)
B( find(A(i)) ) = var_found(i);
end
Please can someone advise

Best Answer

You want to find all the indices of all elements of A in B? So, some elements of A might occur once, other multiple times, and some not at all. Therefore you need to resort to cell arrays. With arrayfun you can loop over all elements of A:
A = [1 2 3 4]
B = [2 2 1 4 2 1]
C = arrayfun(@(x) find(B==x), A, 'un', 0)
% C{k} now holds the indices into B, where B equals A(k)