0

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 2

6

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])

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.