简体   繁体   中英

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.

  1. I am trying to create a list of numbers, that do not include the number 8.

  2. If the code creates an 8, this will mean that exitflag is equal to 1.

  3. Can I adapt this program so that if the exitflag=1 , the it will remove that result and add another loop.

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 .

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:

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 doing what you want, you need to use a while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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