mHelpMe
mHelpMe

Reputation: 6668

logical indexing based on multiple conditions

I am trying to return a logical vector based on multiple search conditions. I thought this was quite simple and sure it probably is.

So I'm just trying a very simple example. I have a vector 10 x 1 of type double, called myVec. Where the element in myVec is equal to 5 or 8 I would like a 1 returned otherwise a 0 returned.

myVec
5
3 
8
9
1
8
5
6
7
5

My result vector should look something like below,

Result
1
0
1
0
0
1
1
0
0
1

I have tried the following,

rl = find(myVec == 8 | myVec == 5);
rl = myVec == 8 | myVec == 5;

Both attempts give the message,

Error: The expression to the left of the equals sign is not a valid target for an assignment.

Update

Here is my actual vector that I was playing with,

 myVec = [3 5 12 34 62 98 45 12 12 64 20 5 5 94 87 21 20]';

Here is the line of code I was trying use that throws the error but appears it should work,

 rl = myVec  == 12 | myVec  == 5 | myVec  = 20;

Upvotes: 2

Views: 1096

Answers (1)

Stewie Griffin
Stewie Griffin

Reputation: 14939

This should do the trick:

myvec = 1:10;
vec = (myvec == 5 | myvec == 8)
vec =

     0     0     0     0     1     0     0     1     0     0

This works without the parentheses too, so there's something else wrong. The find version gives the indices of the elements, also without an error. Actually, I find no way to reproduce your error message.

Upvotes: 2

Related Questions