Reputation: 85
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
Upvotes: 0
Views: 67
Reputation: 60799
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).
Upvotes: 0
Reputation: 26285
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
Upvotes: 2