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.
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.
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.
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.
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.
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'); >> c c = 3 6 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With