Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A conditional statement during a for loop in MATLAB

Tags:

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.

like image 554
user30609 Avatar asked Apr 30 '26 21:04

user30609


1 Answers

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
like image 160
Cris Luengo Avatar answered May 02 '26 17:05

Cris Luengo