简体   繁体   English

MATLAB 中 for 循环期间的条件语句

[英]A conditional statement during a for loop in MATLAB

This is my attempt of a simple example (it seems pointless) but the idea is bigger than this simple code.这是我尝试一个简单的例子(看起来毫无意义),但这个想法比这个简单的代码更大。

During a for loop, if something happens, I want to skip this step of the for loop and then add an extra step on the end.在 for 循环期间,如果发生某些事情,我想跳过 for 循环的这一步,然后在最后添加一个额外的步骤。

  1. I am trying to create a list of numbers, that do not include the number 8.我正在尝试创建一个不包括数字 8 的数字列表。

  2. If the code creates an 8, this will mean that exitflag is equal to 1.如果代码创建一个 8,这将意味着 exitflag 等于 1。

  3. Can I adapt this program so that if the exitflag=1 , the it will remove that result and add another loop.我可以调整这个程序,以便如果exitflag=1 ,它将删除该结果并添加另一个循环。

The code:编码:

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)

I would ideally like a list of numbers, 1000 long which does not contain an 8 .理想情况下,我想要一个不包含81000长的数字列表。

If what you want to do is 1000 iterations of the loop, but repeat a loop iteration if you don't like its result, instead of tagging the repeat at the end, what you can do is loop inside the for loop until you do like the result of that iteration:如果您想要做的是循环的 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

No.不。

With for loop, the number of loops is determined on the loop start and it is not dynamic.使用 for 循环,循环数是在循环开始时确定的,它不是动态的。

For doing what you want, you need to use a while loop.为了做你想做的事,你需要使用一个while循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM