While loop execution with multiple numeric and logical conditions

2 Ansichten (letzte 30 Tage)
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.

Akzeptierte Antwort

Jan
Jan am 27 Apr. 2022
Bearbeitet: Jan am 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 Kommentar
Joseph Dal Bello
Joseph Dal Bello am 27 Apr. 2022
Thanks for the answer!
I think I must have caused an error somewhere through the code repetition, your solution worked perfectly!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by