Find indices of elements in an array based on a search from another array

arrays, find, matlab, matrix, search

Solution

This is actually built into `ismember`. You just need to set the right flag, then it's a one liner and you don't need arrayfun. Versions newer than R2012b use this behavior by default.

Originally, `ismember` would return the last occurence if there are several, the R2012a flag makes it return the first one.

Here's my testing results:

a = [1, 2, 5, 7, 6, 9, 8, 3, 4, 7, 0, 6];
b = [5, 9, 6];

[~,c] = ismember(b,a,'R2012a');
>> c
c =
     3     6     5

Problem

Imagine that i have two arrays: ``` a = [1, 2, 5, 7, 6, 9, 8, 3, 4, 7, 0]; b = [5, 9, 6]; ``` I want to find the indices of the values of b in a (only the first hit) ie: ``` c = [3, 6, 5]; ``` Is there an easy Matlab native way to do this without looping and searching. I have tried to use find() with: ``` find(a == b) ``` and it would work if you did this: ``` for i = 1:length(b) index = find(a == b(i)); c = [c, index(1)] end ``` But it would be ideal for it to be easier then this.

Original source