如何在for循环中更新计数器变量 [英] How to update counter variable in a for loop
问题描述
说我有一个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屋!