While loop execution with multiple numeric and logical conditions
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Joseph Dal Bello
am 27 Apr. 2022
Kommentiert: Joseph Dal Bello
am 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.
0 Kommentare
Akzeptierte Antwort
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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!