如何在for循环中更新计数器变量 [英] How to update counter variable in a for loop

查看:85
本文介绍了如何在for循环中更新计数器变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个for循环,它的计数器k从10减少到1.在循环中,当k变为5时,我将创建k=4.当我在每个循环中输出k时,我希望它会像这样跳过4:

Say I have a for loop that counts from 10 down to 1 with counter k. In the loop, when k becomes 5, I make k=4. When I output k in each loop, I expected it would skip the 4 like so:

10 9 8 7 6 5 3 2 1

相反,我将所有数字从10减少到1,但并没有跳过4.如何使它跳过4?

Instead I got all the numbers from 10 down to 1, it did not skip the 4. How can I make it so that it skips 4?

for k=10:-1:1
   if i==5
      k=i-1;
   end
end

推荐答案

您不能在MATLAB的循环中修改循环索引.您的两个选择是在循环之前忽略该索引值

You cannot modify the loop index from within the loop in MATLAB. Your two options are to omit that that index value prior to the loop

numbers = 10:-1:1;
numbers(numbers == 4) = [];

for k = numbers
    % Stuff
end

或者您可以使用while循环而不是for循环

Or you can use a while loop rather than a for loop

k = 10;
while k > 0

    if k == 5
        k = k - 1;
    end

    k = k - 1;
end

或者您也可以使用continue进行@beaker的建议.

Or you can also do what @beaker has suggested with continue.

这篇关于如何在for循环中更新计数器变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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