フィルターのクリア

How can I skip the rest of an if statement?

50 ビュー (過去 30 日間)
Jing Ci Neo
Jing Ci Neo 2024 年 2 月 20 日
コメント済み: Jing Ci Neo 2024 年 2 月 20 日
Is there a way to skip the rest of an "if" statement if a condition is fulfilled? I want to having many if-else statements. I can't use break because it is only for "for" and "while" loops, is there something similar for "if" statements?
Here is a simple example of my code.
if n > 1
if a == 1
disp('Haha')
break % (Here is where I want to skip the rest of if statement)
end
disp('Nooooo')
end
disp('Done!')

採用された回答

Walter Roberson
Walter Roberson 2024 年 2 月 20 日
if n > 1
while true
if a == 1
disp('Haha')
break % (Here is where I want to skip the rest of if statement)
end
disp('Nooooo')
break;
end
end
disp('Done!')
  1 件のコメント
Jing Ci Neo
Jing Ci Neo 2024 年 2 月 20 日
I think this would work the best for my code, thank you!

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

その他の回答 (2 件)

Hassaan
Hassaan 2024 年 2 月 20 日
編集済み: Hassaan 2024 年 2 月 20 日
if n > 1
if a == 1
disp('Haha')
% No additional commands here - skips directly to the end of the outer if block
else
% This part will only execute if a ~= 1
disp('Nooooo')
end
end
disp('Done!')
In this structure, if a == 1, MATLAB displays "Haha" and then skips to the end of the if block, because there are no other commands to execute in the if a == 1 case. If a is not equal to 1, MATLAB does not enter the first if block and instead goes to the else part, executing whatever commands are there.
Effectively uses the logical structuring of your conditions to control the flow of your code without needing a specific statement to exit an if block.
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
Feel free to contact me.

Torsten
Torsten 2024 年 2 月 20 日
編集済み: Torsten 2024 年 2 月 20 日
Also in for-loops, "break" only exits the inner structure, but the outer loop runs until the end (see below).
Thus you cannot expect that "break" in your nested if structure will exit completely.
for i = 1:10
for j = 1:10
if j==2
break
end
end
i
end
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by