Reputation: 2571
I want to return true if the element of an array b=[1,2,3,4,5]
equals 1 or 2 or 5. How do I do this?
Upvotes: 0
Views: 125
Reputation: 74940
There are different ways to do that:
Test an individual element against one number
b(1) == 5
Test an individual element against several numbers, i.e. is the first element either 1 or 2 or 5?
b(1) == 1 || b(1) == 2 || b(1) == 5
%# which is equivalent to
any(b(1) == [1 2 5];
Test all (or many) elements against one number
b == 1; %# a vector with t/f for each element
Test all elements against several numbers
b == 1 | b == 2 | b == 5 %# note that I can't use the shortcut ||
%# this is equivalent to
ismember(b,[1 2 5])
Upvotes: 6
Reputation: 21351
It is very simple. To test equality of numbers you simply use the ==
operator.
if (b(1) == 5)
%% first element of b is 5
%% now implement code you require
similarly you can test equality for any element in a matrix. To test for multiple values use the logical or operator ||
in conjunction with ==
for example
if (b(1) == 5 || b(1) == 2 || b(1) == 1)
%% first element of b is 1,2 or 5
%% now implement code you require
Upvotes: 3