Testing to see if an if or elseif value is equal to a range of values?

57 views (last 30 days)
So i have the user enter a random number. I then have a series of if and elseif statements saying that if the number falls within this range, print this. How exactly do i do this?
Ex:
if rperiod == [1:6]
fprintf('The cost is $27.\n')
elseif rperiod == [7:27]
fprintf('The cost is $162 for 7 days, +$25 for each additional day.\n')
elseif rperiod == [28:60]
fprintf('The cost is $622 for 28 days,+$23 for each additional day.\n')
else
fprintf('Rental is not available for more than 60 days.\n')
end
This gives me an error on the [1:6] part of it. My understanding is that its testing to see if rperiod falls between 1-6, but i dont think this is correct. What is the right way to do this?

Answers (2)

dpb
dpb on 11 Oct 2013
Matlab == for a vector (your [1:6]) is T iff all elements match. Since there's only one constant it can at most match one of the six values and thus the entire expression evaluates as false.
You can write the expressions to match but I prefer to put that at a lower level with the help of a utility function
function flg=iswithin(x,lo,hi)
% returns T for values within range of input
% SYNTAX:
% [log] = iswithin(x,lo,hi)
% returns T for x between lo and hi values, inclusive
flg= (x>=lo) & (x<=hi);
Then you can write something like
if iswithin(rperiod,1,6)
fprintf('The cost is $27.
...
etc. Also switch...case...end is a useful construct for such cases with multiple choices

Jos (10584)
Jos (10584) on 11 Oct 2013
To compare an element with a range or with a set, these three examples might be useful to see:
if x >= 1 && x <6
disp('X is within the half-open range [1, 6)') ;
end
if ismember(X, [1 2 99])
disp('X is an element of the set {1 2 99}') ;
end
% or ...
if any(x==[1 2 99])
disp('X is an element of the set {1 2 99}') ;
end

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!