Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 358
Fantastic Mr Fox Avatar asked Jul 20 '12 02:07

Fantastic Mr Fox


People also ask

How do you search and get the index of a value in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

Can you access an array element by referring to the index?

Referring to array elements You can refer to the first element of the array as myArray[0] , the second element of the array as myArray[1] , etc… The index of the elements begins with zero. Note: You can also use property accessors to access other properties of the array, like with an object.

How do you search within an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

How do you find the index of an element in an array in Matlab?

k = find( X ) returns a vector containing the linear indices of each nonzero element in array X . If X is a vector, then find returns a vector with the same orientation as X . If X is a multidimensional array, then find returns a column vector of the linear indices of the result.


2 Answers

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).

like image 160
Gunther Struyf Avatar answered Oct 07 '22 16:10

Gunther Struyf


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 
like image 27
scenia Avatar answered Oct 07 '22 16:10

scenia