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.CommentedMar 27 at 18:33
  • Ohhhh... I see. Thank you! That makes a lot of sense :)CommentedMar 27 at 18:35
  • 3
    Use break or return to exit the for loop early.
    – horchler
    CommentedMar 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 

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.