如果满足条件,则在当前迭代步骤结束时退出循环

问题描述 投票:4回答:4

我遇到的一个常见问题如下:

在循环内(通常是for循环),一些约束是 - 并且必须 - 在开始时进行检查。现在有时如果条件满足,循环中的代码应该运行到当前迭代步骤的末尾然后退出。

通常我会以某种方式这样做

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

但是在一个紧密的循环中,已经检查if (quit == 1)的额外条件可能会导致相关的减速。还需要引入一个额外的变量,所以我想知道这通常是怎么做的,或者是否有更好的方法来做...

matlab loops for-loop octave
4个回答
0
投票

为什么不这样做呢。

for i = 1:1:11
  if (a == 5)    % Condition to be checked *before* the calculation
    func()  --> do all the calculations
    break;    % Stop loop after this iteration
  else 
    func()   --> do all calculations
  end
end

function func()
 a = a+1
 //all other calculations
end

0
投票

通常,您可以检测何时停止迭代。但是,如果我理解你的问题,你只能检测它应该是最后一次迭代的时间。你可以试试这个:

a = 0;
i = 1;
while (i<=11)
    if (a == 5)
        i = 12;    % Make sure this is the last iteration
    else
        i = i + 1;
    end

    a = a + 1;
end

0
投票

关于什么:

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

有什么区别?


0
投票
- Make an infinite loop with logical variable condition set to 1
- Within the loop when stopping loop criteria rises set the logical 
  variable condition to 0
- loop will no longer run 



count = 0;
stop = 11;
condition = 1;
while condition
      count = count + 1;
      --> do all the calculations before checking 
      condition = ~(a == 5 || count == stop);
      --> do all the remaining calculations then exit from the loop      
end
© www.soinside.com 2019 - 2024. All rights reserved.