While loop execution with multiple numeric and logical conditions

1 view (last 30 days)
Joseph Dal Bello
Joseph Dal Bello on 27 Apr 2022
Commented: Joseph Dal Bello on 27 Apr 2022
I am unsure how to write a while loop that will run to check if an input is not within a specified domain and is also not numeric.
%ask for input
a = input('Select from list: ','s');
a = str2double(a);
while (a < 1 || a > 3 || ~(isfinite(a)) )
%display error message if input is invalid and ask for input again
fprintf('\nInput invalid\n')
a = input('Select from list: ','s');
a = str2double(a);
end
When I input a number greater than 1, the input passes the while loop and continues with the program.
Any help appreciated.

Accepted Answer

Jan
Jan on 27 Apr 2022
Edited: Jan on 27 Apr 2022
The code looks fine. Do you have a problem with it?
It is a good programming practice to avoid repeated code. Maybe this is "cleaner":
%ask for input
ready = false;
while ~ready
a = input('Select from list: ');
ready = (a >=1 && a <= 3); % Then it must be finite also...
if ~ready
fprintf('\nInput invalid\n')
end
end
Now you have one input command only. If you want to modify the text of the input command, you do not have to remember to change it at 2 locations.
If you use input() without the 's' flag, not-numerical inputs are avoided directly.
  1 Comment
Joseph Dal Bello
Joseph Dal Bello on 27 Apr 2022
Thanks for the answer!
I think I must have caused an error somewhere through the code repetition, your solution worked perfectly!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!