How to jump to a particular place in the for loop if the if condition is satisfied?

喜你入骨 提交于 2019-12-02 11:53:05

Replace the for loop with a while loop to have a bit more flexibility. The only difference is that you have to manually increment i, hence this also allows you to not increment i.

Given your new requirement, you can keep track of the number of attempts, and easily change this if needed:

file = dir('*.jpg');
n = length(file);

i = 1;
attempts = 1; 

while i <= n
    % perform code on i'th file
    success =  doSomething(); % set success true or false;

    if success
        % increment to go to next file
        i = i + 1;

    elseif ~success && attempts <= 2 % failed, but gave it only one try
        % increment number of attempts, to prevent performing 
        attempts = attempts + 1;
    else % failed, and max attempts reached, increment to go to next file
        i = i + 1;
        % reset number of attempts 
        attempts = 1;
    end
end

Given the new requirement, added after rinkert's answer, the simplest approach becomes separating out code from your loop in a separate function:

function main_function

  file = dir('*.jpg');
  n = length(file);
  for i = 1:n
    some_operations(i);
    if 'condition'
      some_operations(i);
    end
  end

  function some_operations(i)
    % Here you can access file(i), since this function has access to the variables defined in main_function
    *perform some operations on the 'i'th file*
  end

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