最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

For loop inside While loop not breaking - Matlab - Stack Overflow

programmeradmin3浏览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!

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!

Share Improve this question asked Mar 27 at 18:30 Alexander SavadelisAlexander Savadelis 214 bronze badges 3
  • 4 Because a while loop only checks its guard at the start of each iteration. – Scott Hunter Commented Mar 27 at 18:33
  • Ohhhh... I see. Thank you! That makes a lot of sense :) – Alexander Savadelis Commented Mar 27 at 18:35
  • 2 Use break or return to exit the for loop early. – horchler Commented Mar 27 at 20:02
Add a comment  | 

1 Answer 1

Reset to default 4

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
发布评论

评论列表(0)

  1. 暂无评论