TYL
TYL

Reputation: 1637

Find first occurrence of any number of a vector

I want to find the first occurrence of either 2,3 or 5 in x. The output should be 7 as 3 appears first at index 7. How do I do that?

x = [0 0 0 0 1 1 3 5 2 0 0];
y = [2 3 5]; 

output = 7

I can use find(x == 3, 1) to find just one number but how do I do that for multiple numbers?

Thanks

Upvotes: 1

Views: 857

Answers (2)

gehbiszumeis
gehbiszumeis

Reputation: 3711

MATLABs find is already the right choice in combination with ismember

In this case

>> find(ismember(x,y),1)

will do what you want. It returns the index of the first occurence of array y in array x. This will work for any lengths y might have.

Upvotes: 4

matanj
matanj

Reputation: 362

Find() accepts a logical term as an argument, so you can use your call but instead of checking only for 3, use something like: (x==2 || x==3 || x==5)

I'm general, you might want to use the intersect() function.

Upvotes: 1

Related Questions