0
Flag = 0;

while Flag == 0
    for x = 1:10
        if x == 3
            Flag = 1;
        end % end: if
    end % end; for
end % end: while

Can anyone tell me why the while loop condition is not triggering when x is three? It runs the entire for loop and I get a value of 10. I am trying to have a flag trigger when a specific condition is met in the for loop.

Thank you!

3
  • 5
    Because a while loop only checks its guard at the start of each iteration. Commented Mar 27 at 18:33
  • Ohhhh... I see. Thank you! That makes a lot of sense :) Commented Mar 27 at 18:35
  • 3
    Use break or return to exit the for loop early. Commented Mar 27 at 20:02

1 Answer 1

5

If you want to break out of the for loop early then you should use break

Flag = 0;

while Flag == 0
    for x = 1:10
        if x == 3
            Flag = 1;
            break     % Exit the 'for' loop
        end
    end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.