Use of break in if?
308 次查看(过去 30 天)
显示 更早的评论
Here is my code i Want to use break/continue after First if Ends. as i have mention it there. but we cant use break in IF. I need alternative of it. Note: there are two times if(Stroke_counter==1) in code. that is not because of mistake
if(Stroke_counter==1)
if (((S==1)||(E==1)) &&( (y==2)) )
msgbox('This is One','Recognize');
end
elseif( (x==1)&&(y==1)&&(x==1) &&(y==1) &&(S==2))
msgbox('This is two','Recognize');
end
elseif((x==1)&&(y==1)&&(x~=1))
msgbox('This is three','Recognize');
end
beak;
else
msgbox('Not Found...','error');
end
else
msgbox('Not in 1 step','error');
end
if(Stroke_counter==1)
if (((S==1)||(D==1)) &&( (y==2)) )
msgbox('This is four','Recognize');
end
elseif( (x==1)&&(y==1)&&(D==1) &&(y==1) &&(S==2))
msgbox('This is five','Recognize');
end
elseif((x==1)&&(F==1)&&(x~=1))
msgbox('This is Six','Recognize');
end
else
msgbox('Not Found...','error');
end
else
msgbox('Not in 2 step','error');
2 个评论
David Sanchez
2014-8-20
What is the point on using a break within an if statement?
If the condition is fulfilled, the following else will not count in your code anyway.
Lorenzo TORRICELLI
2021-4-15
For example, if a block of instructions is common to a number of conditions, whereas a certain case is exceptional.
采纳的回答
Adam
2014-8-20
If you want to break after the first If ends then you won't be in the If to place your break/continue. And if you were able to place one there then why not just delete the second if since it would never execute.
3 个评论
Adam
2014-8-20
Just use a boolean then as
answerFound = false;
then update it in each if statement and then AND it together with the following if statements as e.g.
if( ~answerFound && Stroke_counter==1)
To be honest though this sounds like such a large block of code it should be a function by itself (probably many, but that's a side issue) so you can just put
return
to return early from the current function and then carry on your algorithm in the function that calls this one.
更多回答(1 个)
Jan
2021-4-15
"MAtlab donot work in more than 6 (if() elseif() else end)" - of course Matlab handles much more nested IF branchs than 6.
Checking a lot of different conditions with a pile of IF commands creates code, which is hard to read and to debug. It is too prone to typos like in your code:
((x==1) && (y==1) && (x~=1))
This cannot be TRUE, because x==1 && x~=1 cannot happen. So it is not Matlab, but the programming style, which causes problems here.
This is not useful also:
elseif( (x==1) && (y==1) && (x==1) && (y==1) &&(S==2))
% ^^^^^^^^^^^^^^^^ tested twice ?!
Your code is not valid at all due to the orphand end commands:
if (((S==1)||(E==1)) &&( (y==2)) )
msgbox('This is One','Recognize');
end % <== Nope, no END before ELSEIF
elseif
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!