0

I have a vector that looks like this

A = [1 2 3 1 2 3 1 2 3] 

and I would like to write a function that returns True if there is a number between 5 to 9 or False if not

1
  • 1
    The documentation for any should get you most of the way there Commented Aug 15, 2018 at 14:51

2 Answers 2

2

As suggested by etmuse, you can just use any with two conditions.

function output = findelem(A) if(any(A>5 & A<9)) output = true; return; end output = false; end 

Call function:

>>findelem([1 2 3 1 2 3 1 2 3]) returns logical 0 >>findelem([1 2 3 1 6 3 1 2 3]) returns logical 1 

As @beaker correctly points out, you can simply use:

function output = findelem(A) output = (any(A>5 & A<9)) end 
Sign up to request clarification or add additional context in comments.

4 Comments

any returns a boolean value. The if/else seems wasteful.
Yeah true, I added that in now, thanks. It was more for didactical purposes.
There was no else by the way :P
I realize that, but "if with return, otherwise falling through to a default assignment" was less concise.
0

An alternative solution uses ismember:

any(ismember(5:9,A)) 

It checks if any of the elements in 5:9 is present in A. If you leave out the any, it will tell you which of the elements is present in A:

>> ismember([1,5,9],A) ans = 1 0 0 

(indicating that 1 is present, but 5 and 9 are not).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.