MATLAB Answers

0

Need some assistance with "if" command

Aaron 님이 질문을 제출함. 28 Jun 2012
I'm trying to get my program to stop completely when given an invalid response after entering the side lengths. I've created the following:
a=input('Enter value for side a: ');
if a < 0
disp('Not a valid input.')
end
b=input('Enter value for side b: ');
if b < 0
disp('Not a valid input.')
end
c=input('Enter value for side c: ');
if c < 0
disp('Not a valid input.')

  댓글 수: 0

로그인 to comment.

태그

답변 수: 3

Geoff 님의 답변 28 Jun 2012
Geoff 님이 편집함. 28 Jun 2012
 채택된 답변

If you don't have a function or anything to return from, there's a sneaky little trick you can use. This can be useful for other things too...
ok = false;
while 1
a=input('Enter value for side a: ');
if a < 0, break; end
b=input('Enter value for side b: ');
if b < 0, break; end
c=input('Enter value for side c: ');
if c < 0, break; end
ok = true;
break;
end
if ok
% Do your thing here....
else
disp('Not a valid input.');
end
Err... Bear in mind this isn't the best of programming practices. =)

  댓글 수: 0

로그인 to comment.


Geoff 님의 답변 28 Jun 2012

Oh, the better way is to use the proper MATLAB error function:
if a < 0
error( 'Not a valid input.' );
end

  댓글 수: 0

로그인 to comment.


Walter Roberson 님의 답변 28 Jun 2012

To get your program to stop completely you are going to need to use the command "quit", as anything else you can voluntarily do has the risk of being intercepted by a different level, such as by a try/catch block. "quit" will exit MATLAB.
Honestly, even "quit" might not be good enough, as I think "quit" would still end up running any registered onCleanup() routines rather than stopping the program completely. So possibly what you should do is write a little mex routine that deliberately dereferences an invalid pointer so that MATLAB crashes.

  댓글 수: 0

로그인 to comment.



Translated by