Exit loop at the end of current iteration step if condition is fulfilled

时光毁灭记忆、已成空白 提交于 2019-12-10 18:02:39

问题


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...


回答1:


why not do this way.

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



回答2:


Normally you can detect when to stop iterating. But if I understand your question, you can only detect when it should be the last iteration. You could try this:

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



回答3:


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?




回答4:


- 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


来源:https://stackoverflow.com/questions/25264152/exit-loop-at-the-end-of-current-iteration-step-if-condition-is-fulfilled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!