如果满足if条件,如何跳至for循环中的特定位置?

时间:2019-04-12 16:05:58

标签: matlab for-loop if-statement conditional goto

我有一些图像文件。我正在尝试使用每个文件执行一些计算,如果满足特定条件,我想回到代码中的特定行,然后从那里再次运行它。但是只有一次。不管第二次是否满足if条件,我都想转到下一个迭代。但是,MATLAB似乎没有goto函数,而且,使用goto隐含错误的编程,所以我认为我会针对满足if条件的特定“ i”值对for循环进行两次迭代。

file = dir('*.jpg');
n = length(file);
for i = 1:n
    *perform some operations on the 'i'th file*
    if 'condition'
        *run the for loop again for the 'i'th file instead of going to the 'i+1'th file*
         i=i-1;
    else
        *go to next iteration*
    end
end

我试图通过将循环内的循环变量'i'更改为'i-1'进行编码,以便在下一次迭代中,将再次重复'i'个循环,但这样做给出了错误的信息输出,尽管我不知道代码中是否还有其他错误,或者内部更改循环变量是否是问题的原因。对此有任何帮助。

2 个答案:

答案 0 :(得分:4)

for循环替换为while循环,以提高灵活性。唯一的区别是您必须手动递增i,因此这也使您不必递增i

鉴于您的新要求,您可以跟踪尝试次数,并在需要时轻松更改此尝试:

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

答案 1 :(得分:1)

鉴于在rinkert's answer之后添加的新要求,最简单的方法是在单独的函数中将代码与循环分离:

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