How to limit the user input to a specific range?

9 views (last 30 days)
Hi, I want to print in the command prompt "Enter the length in meters" adding a limitation that the input must be between o to 10. If something falls outside the range, the sentence "Not a valid number. Please try again" will be displayed. I tried with the following but Matlab disregard the condition. How should I define it instead?
while 1
len = str2double(input('Enter the length in meters: ','s'));
if len
break;
end
disp('Not a valid number. Please try again')
end
Thanks for your time.

Accepted Answer

Geoff Hayes
Geoff Hayes on 7 Jun 2017
Edited: Geoff Hayes on 7 Jun 2017
Valentina - your condition is
if len
This will always be true if len is not zero. If you wish to restrict your length to the interval 0 and 10, then your condition would be
if len >= 0 && len <= 10
break;
end
  2 Comments
Kundera
Kundera on 7 Jun 2017
Thank you. It works perfectly, but still I don't understand one thing. I want the range to include the ending 0 and 10. Using your code it works, but I don't see why of using the output 0. To me, if the input is 0, the condition len >= 0 should break and send me the 'Not a valid number. Please try again'. But it is not the case.
Geoff Hayes
Geoff Hayes on 7 Jun 2017
But isn't 0 a valid length? From your original comment, that the input must be between o to 10. If 0 is invalid, then change your condition to
if len > 0 && len <= 10
break;
end

Sign in to comment.

More Answers (0)

Categories

Find more on External Language Interfaces 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!