MATLAB: Find multiple elements in an array.

arrayfind

I have an array a = [1 5 2 5 3 5 4 5]. I have a second array b = [2,3,4].
I want to type something like c = find(a == b), but Matlab doesn't like it that the dimensions don't agree. The answer I am looking for is c = [3,5,7].
I know I could do it with a for loop. Trying to avoid a for loop for speed concerns. Any help would be appreciated.

Best Answer

Use ismember:
a = [1 5 2 5 3 5 4 5]
b = [2,3,4]
% Give "true" if the element in "a" is a member of "b".
c = ismember(a, b)
% Extract the elements of a at those indexes.
indexes = find(c)
Results:
a =
1 5 2 5 3 5 4 5
b =
2 3 4
c =
0 0 1 0 1 0 1 0
indexes =
3 5 7
Obviously you can do away with "c" if you want, and just have a one-liner. I did it in two steps just for tutorial purposes.