필터 지우기
필터 지우기

How can I skip the rest of an if statement?

조회 수: 48 (최근 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 CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by