如果满足if条件,如何跳至for循环中的特定位置? [英] How to jump to a particular place in the for loop if the if condition is satisfied?

查看:456
本文介绍了如果满足if条件,如何跳至for循环中的特定位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some image files. I'm trying to perform some calculations using each file and if a certain condition is met, I'd like to go back to a particular line in the code and run it from there once more. But only just once again. Regardless of whether the if condition is satisfied or not satisfied the second time, I want to go to the next iteration. But, MATLAB doesn't seem to have a goto function and also, using goto implies bad programming so I thought I'd just iterate the for loop twice for a particular 'i' value which satisfies the if condition.

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'个循环,但这样做是为了错误的输出,尽管我不知道代码中是否还有其他错误,或者内部更改循环变量是否是问题的原因。对此提供了任何帮助。

I have tried to code this by changing the loop variable 'i' inside the loop to 'i-1' so that on the next iteration, the 'i'th loop will be repeated again but doing so is giving the wrong output, though I don't know if there is some other error in my code or if the changing of the loop variable internally is the cause of the problem. Any help on this is appreciated.

推荐答案

for 循环替换为 while 循环具有更大的灵活性。唯一的区别是您必须手动增加 i ,因此这也使您不能增加 i

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

这篇关于如果满足if条件,如何跳至for循环中的特定位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆