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

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


You can compact your for loop easily with arrayfun into a simple one-liner:

arrayfun(@(x) find(a == x,1,'first'), b )

also see Scenia's answer for newer matlab versions (>R2012b).


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');>> cc =     3     6     5


This is a fix to the ismember approach that @Pursuit suggested. This way it handles multiple occurrences of one of the numbers, and returns the result in the correct order:

[tf,loc] = ismember(a,b);tf = find(tf);[~,idx] = unique(loc(tf), 'first');c = tf(idx);

The result:

>> cc =     3     6     5