Help with error command and user input

조회 수: 6 (최근 30일)
Stevie Rauch
Stevie Rauch 2020년 4월 18일
댓글: Sriram Tadavarty 2020년 4월 18일
Below I have a simple user input asking for an angle. I am currently displaying an error if the user does not pick a valid angle, they will then have to rerun the code in order to try again. I am trying to have a while loop that doesn't continue on until the statement is true but I am having trouble with my arguments. I originally tried,
A = input('Pick an angle 15, 30, 45 or 60 degreees. Angle = ');
while A ~= [15 30 45 60]
A = input('Pick an angle 15, 30, 45 or 60 degreees. Angle = ');
if A ~= [15 30 45 60]
error('angle must be 15, 30, 45, or 60 degrees');
end
end
but this brings a problem because the if statement is never reached. Currently i have
A = input('Pick an angle 15, 30, 45, or 60 angle = ');
if A ~= ([15 30 45 60])
error('angle must be 15, 30, 45, or 60 degrees ');
end
any help is appreciated.
  댓글 수: 3
Stevie Rauch
Stevie Rauch 2020년 4월 18일
could i out an error message and prompt the user for another input if i use if all?
darova
darova 2020년 4월 18일
This is the solution. Yes

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

답변 (1개)

Sriram Tadavarty
Sriram Tadavarty 2020년 4월 18일
Hi Stieve,
You can try running the infinite loop, till the input provided is one of the valid values.
Once, you place the error in the code, the execution stops. Indeed you can place the message with the disp command.
Here is the way the code can be placed.
A = input('Pick an angle 15, 30, 45 or 60 degreees. Angle = ');
while (1)
if any(A == [15 30 45 60])
break;
else
disp('angle must be 15, 30, 45, 0r 60 degrees') % This is to indicate what the valid values are
A = input('Pick an angle 15, 30, 45 or 60 degreees. Angle = ');
end
end
Hope this helps.
Regards,
Sriram
  댓글 수: 2
Stevie Rauch
Stevie Rauch 2020년 4월 18일
Ahh I see so one cannot prompt the user for an input after an error message in the code. They simply have to restart it?
Sriram Tadavarty
Sriram Tadavarty 2020년 4월 18일
If you use error command, then they have to restart the code. You can use warning or disp as suggested.
error will stop the execution once it reaches it.
Hope this helps.
Regards,
Sriram

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by