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?
2 Answers
There are different ways to do that:
Test an individual element against one number
b(1) == 5Test 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 toany(b(1) == [1 2 5];Test all (or many) elements against one number
b == 1; %# a vector with t/f for each elementTest all elements against several numbers
b == 1 | b == 2 | b == 5 %# note that I can't use the shortcut ||%# this is equivalent toismember(b,[1 2 5])
Comments
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