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
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
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 any returns a boolean value. The if/else seems wasteful.else by the way :Pif with return, otherwise falling through to a default assignment" was less concise.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).