How to skip lines to execute/run?

39 ビュー (過去 30 日間)
Benjamin
Benjamin 2020 年 5 月 28 日
編集済み: Brent Kostich 2020 年 5 月 29 日
HI all
I have a simple question. I want to put a line before a section of my program that if its value is for example "No" then skip some or rest of the lines in the program. I mean like:
YesNo = "No" % Yes or No
if YesNo == "No"
...skip...
...skip...
OR
if YesNo == "Yes"
...run...
...run...
so, is there any command that skips the rest of the lines to be executed?
PS. I don't have loops to use the continue command.
Thank you very much.
  3 件のコメント
Benjamin
Benjamin 2020 年 5 月 28 日
Dear Brent
I want to know if there is any command that skips the rest of the lines?
Brent Kostich
Brent Kostich 2020 年 5 月 29 日
編集済み: Brent Kostich 2020 年 5 月 29 日
See answer below.

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

回答 (3 件)

Brent Kostich
Brent Kostich 2020 年 5 月 29 日
The solution to your problem depends on what you mean by "skip". If you want a segment of code that runs for one case, and different segment of code that runs for another, then a simple if-else statement would work:
flag = true;
if flag
% code inside this block will run
else
% code inside this block will not run
end
% ...
% [some more code]
Using the if-else statemtent will run one bit of code and not the other, then it will continue to run any code that is after it. However, if you are trying to set up a flag that skips all the rest of the code, then put all your code in a function and use a return statement, like so:
function [out_args] = someFunction(in_args)
% ... beginning code
flag = true;
if flag
return
end
% ... rest of code
In this case, any code above the if-statement will run. If the flag value is true then the function will terminate and not run any of the later code. If the flag value is false then the code will continue to run to the end of the function.
If you use a function be sure to output some intermediate value for out_args (if necessary) when you use the return statement.

Tommy
Tommy 2020 年 5 月 28 日
return % ?
Or have your if block encompass the lines to be skipped and change the condition to the opposite of your condition for skipping.

Rik
Rik 2020 年 5 月 28 日
You should be using strcmp to compare strings or chars, but otherwise what you describe is exactly what you need to do (well, one of the things you could do):
SomeFlag=false;
if SomeFlag
%code that will not run
else
%code that will run
end

カテゴリ

Help Center および File ExchangeInstall Products についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by