首页 > 解决方案 > MATLAB 中 for 循环期间的条件语句

问题描述

这是我尝试一个简单的例子(看起来毫无意义),但这个想法比这个简单的代码更大。

在 for 循环期间,如果发生某些事情,我想跳过 for 循环的这一步,然后在最后添加一个额外的步骤。

  1. 我正在尝试创建一个不包括数字 8 的数字列表。

  2. 如果代码创建一个 8,这将意味着 exitflag 等于 1。

  3. 我可以调整这个程序,以便如果exitflag=1, 它将删除该结果并添加另一个循环。

编码:

for i = 1:1000
    j = 1+round(rand*10)
    if j == 8
        exitflag = 1
    else
        exitflag = 0 
    end
    storeexit(i)=exitflag;
    storej(i)=j;
end
sum(storeexit)

理想情况下,我想要一个1000不包含8.

标签: matlab

解决方案


如果您想要做的是循环的 1000 次迭代,但如果您不喜欢它的结果,则重复for循环迭代,而不是在末尾标记重复,您可以做的是在循环内循环,直到您喜欢该迭代的结果:

stores = zeros(1000,1); % Note that it is important to preallocate arrays, even in toy examples :)
for i = 1:1000
    success = false; % MATLAB has no do..while loop, this is slightly more awkward....
    while ~success
       j = 1+round(rand*10);
       success = j ~= 8;
    end
    storej(i) = j; % j guaranteed to not be 8
end

推荐阅读