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

问题描述 投票:0回答:2

我有一些图像文件。我正在尝试使用每个文件执行一些计算,如果满足某个条件,我想回到代码中的特定行并再次从那里运行它。但只是再一次。无论第二次是否满足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'th循环将再次重复,但这样做会给出错误的输出,尽管我不知道我的代码中是否存在其他错误,或者内部是否更改了循环变量是导致问题的原因。对此有任何帮助表示赞赏。

matlab for-loop if-statement conditional goto
2个回答
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
投票

鉴于新的要求,在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
© www.soinside.com 2019 - 2024. All rights reserved.