tomasz74
tomasz74

Reputation: 16701

matlab indexing with multiple condition

I can't figure out how to create a vector based on condition on more than one other vectors. I have three vectors and I need values of one vector if values on other vectors comply to condition. As an example below I would like to choose values from vector a if values on vector b==2 and values on vector c==0 obviously I expect [2 4]

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

I thought something like:

d = a(b==2) & a(c==0)

but I have d = 1 1 1 1 1 not sure why. It seems to be basic problem but I can find solution for it.

Upvotes: 2

Views: 151

Answers (2)

Divakar
Divakar

Reputation: 221684

Use ismember to find the matching indices along the rows after concatenating b and c and then index to a.

Code

a(ismember([b;c]',[2 0],'rows'))

Output

ans =

     2
     4

You may use bsxfun too for the same result -

a(all(bsxfun(@eq,[b;c],[2 0]'),1))

Or you may just tweak your method to get the correct result -

a(b==2 & c==0)

Upvotes: 2

Paolo
Paolo

Reputation: 76

In your case you can consider using a(b==2 & c==0)

Upvotes: 5

Related Questions