While loop execution with multiple numeric and logical conditions
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Jan
2022-4-27
编辑:Jan
2022-4-27
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!