【问题标题】:How to jump to a particular place in the for loop if the if condition is satisfied?如果满足 if 条件,如何跳转到 for 循环中的特定位置?
【发布时间】:2019-09-03 10:55:41
【问题描述】:

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

【问题讨论】:

  • MATLAB for 循环不适用于增量,它会遍历您在顶部创建的列表 1:n。所以在循环内更改i 对下一次迭代没有影响。

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


【解决方案1】:

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

【讨论】:

  • 我认为在if条件中不应该对i进行任何修改。
  • 如果满足 if 条件,我只想再次运行代码。但是我认为在您的代码中,只要满足 if 条件,代码就会继续运行第 i 次迭代。我将编辑我的问题以使其更清楚。
【解决方案2】:

鉴于在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

【讨论】:

  • 谢谢,但有没有一种方法可以做到这一点,而不必将代码分成函数,也许使用一些变量?
  • @Matte,当然你可以让它更复杂,但为什么呢?这是迄今为止最简单和最易读的解决方案。您确实知道可以在与主函数相同的 M 文件中编写私有函数,对吧?自最近几个版本以来,您甚至可以在脚本 M 文件中编写私有函数。如果这个私有函数是在另一个函数中声明的,它甚至会共享数据,所以你不需要传递任何东西。我会更新答案以反映这一点。
  • 我没有经常使用函数,所以我觉得它们有些混乱。不过我会试试的,谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多