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.

채택된 답변

Jan
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.
  댓글 수: 1
Joseph Dal Bello
Joseph Dal Bello 2022년 4월 27일
Thanks for the answer!
I think I must have caused an error somewhere through the code repetition, your solution worked perfectly!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by