MATLAB Answers

How to stop a script if conditions are met.

3,087 ビュー (過去 30 日間)
Cory
Cory 2012 年 2 月 2 日
コメント済み: Jingyang Xie 2021 年 1 月 6 日 19:50
I am using the 'if' function to detect if a user inputs a number that is not 5 digits long. What I would like is a function that stops the script if a certain condition is met without displaying an error message.
P.S. I'm very new to MATLAB.

  1 件のコメント

Jingyang Xie
Jingyang Xie 2021 年 1 月 6 日 19:50
Hi Cory, have you solved this problem? I think I encountered the same problem...

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2012 年 2 月 2 日
編集済み: MathWorks Support Team 2018 年 11 月 9 日
To stop running a script or function and return to the invoking function or command window, use the return function. For example,
if a > b
return
end
Any code in the current script or function that is after the return function is not run

  2 件のコメント

Hao Cheng
Hao Cheng 2019 年 2 月 11 日
"return" will terminate the current function and go back to the function that calls it. Is it possible then to stop running the entire script in GUI?
For example. A button's Callback function calls another function F. How to stop the Callback function as well if certain critieria in function F is met?
Diaa
Diaa 2019 年 3 月 12 日

サインインしてコメントする。

その他の回答 (1 件)

Hamid Ramezani
Hamid Ramezani 2019 年 9 月 30 日
you may use "error" function instead of return

  3 件のコメント

Walter Roberson
Walter Roberson 2019 年 9 月 30 日
However, "without displaying an error message" is part of the requirement here.
Adam K
Adam K 2020 年 12 月 10 日
I think a 'msgbox' to really alert the user what is the issue, and then the 'error' funcition to stop the code would be a workaround. This way the user is aware that the issue is not really an 'error' when they see the red error font.
msg = "You've got a number that is not 5 digits long";
f = msgbox(msg)
error(msg)
Rik
Rik 2020 年 12 月 10 日
I wonder if it is possible to detect if the code is running in a try block. In such cases the message might be more confusing than simply throwing the error.

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by