如果满足条件,则在当前迭代步骤结束时退出循环 [英] Exit loop at the end of current iteration step if condition is fulfilled
问题描述
在一个循环中(通常是一个for循环),一些约束是 - 必须请在开始时检查 。现在有时如果条件满足,循环内的代码应该运行到当前迭代步骤的结尾,然后退出。
通常我会这样做,不管怎样,这样的
a = 0;
quit = 0;
对于i = 1:1:11
if(a == 5)%要检查的条件*计算之前
quit = 1; %迭代后的停止循环
结束
a = a + 1; %计算
...
if(quit == 1)
break;
end
end
但是, code> if(quit == 1)可能会导致相关的减速。还有一个需要引入额外的变量,所以我不知道这是如何通常这样做,或者如果有更好的方式来做到这一点...
那么:
for i = 1:11
quit =(a == 5); %要检查的条件*计算前
a = a + 1
如果退出
break; %迭代后的停止循环
end
end
有什么区别? / p>
A common problem I have is the following:
Within a loop (usually a for loop) some constraints are - and have to be - checked at the beginning. Now sometimes if a condition if fulfilled, the code within the loop should run to the end of the current iteration step and then quit.
Usually I'd do it somehow like so
a = 0;
quit = 0;
for i = 1:1:11
if (a == 5) % Condition to be checked *before* the calculation
quit = 1; % Stop loop after this iteration
end
a = a + 1; % Calculation
...
if (quit == 1)
break;
end
end
But in a tight loop already this extra condition checking if (quit == 1)
might give a relevant slow down. Also one needs to introduce an extra variable so I wonder how this is usually done or if there is a better way to do it...
What about:
for i = 1:11
quit = (a==5); % Condition to be checked *before* the calculation
a = a+1
if quit
break; % Stop loop after this iteration
end
end
Makes any difference?
这篇关于如果满足条件,则在当前迭代步骤结束时退出循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!