{"id":105,"date":"2007-08-29T13:26:24","date_gmt":"2007-08-29T18:26:24","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2007\/08\/29\/for-versus-while\/"},"modified":"2007-08-30T09:51:01","modified_gmt":"2007-08-30T14:51:01","slug":"for-versus-while","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2007\/08\/29\/for-versus-while\/","title":{"rendered":"for Versus while"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>A reader suggested I discuss the difference in use of MATLAB's <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/for.html\"><tt>for<\/tt><\/a> and <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/while.html\"><tt>while<\/tt><\/a> constructs.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">The Scene<\/a><\/li>\r\n         <li><a href=\"#2\">At Least Once in a while<\/a><\/li>\r\n         <li><a href=\"#5\">Taking Care Using for<\/a><\/li>\r\n         <li><a href=\"#9\">Your Style Preferences?<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>The Scene<a name=\"1\"><\/a><\/h3>\r\n   <p>You want to run some code at least once, regardless of any conditions. You might want to run it more often, depending on some\r\n      conditions.\r\n   <\/p>\r\n   <h3>At Least Once in a while<a name=\"2\"><\/a><\/h3>\r\n   <p>Here's a couple of solutions using a <tt>while<\/tt> construct, while ensuring the main chunk of code is run at least once, even if the stop condition is already met.\r\n   <\/p><pre>  n = 0;\r\n  i = 1;\r\n  while true\r\n       doStuff();\r\n       if (i &gt; n)\r\n           break;\r\n       end\r\n       i = i + 1;\r\n       n = somethingElse();\r\n  end<\/pre><p>Here's another way that inverts the logic surrounding the condition and avoids using an explicit <tt>break<\/tt> statement.  Instead, it has to check to see that <tt>currentState<\/tt> is still <tt>true<\/tt>.\r\n   <\/p><pre>  n = 0;\r\n  i = 1;\r\n  currentState = true;\r\n  while currentState\r\n       doStuff();\r\n       currentState = (i &lt;= n);\r\n       if currentState,\r\n          i = i + 1;\r\n          n = somethingElse();\r\n       end\r\n  end<\/pre><p>I wonder if this version is any better than the first.  It is one line longer so <tt>currentState<\/tt> can be explicitly set.  This might be more readable to some of you, and less so to others.\r\n   <\/p>\r\n   <h3>Taking Care Using for<a name=\"5\"><\/a><\/h3>\r\n   <p>To make sure the code <tt>doStuff<\/tt> runs at least once, we need to take care using a <tt>for<\/tt>-loop.  The reason for this is that the loop code is guaranteed to not run at all if the loop counter variable is empty. \r\n      To ensure the code runs once, we need to repeat the code outside the loop. If the code being run is like this example, encapsulated\r\n      in another function, then it's not so difficult to be sure we've got things right.\r\n   <\/p>\r\n   <p>If instead of a single function, we have several statements to run, then we have take care to copy all of the code and ensure\r\n      that we update both sets if we ever have to make some changes.\r\n   <\/p>\r\n   <p><tt>doStuff<\/tt> will never be run with the following code sample.\r\n   <\/p><pre>  n = 0;\r\n  count = 0;\r\n  for ind = 1:n\r\n      doStuff();\r\n      count = count + 1;\r\n  end<\/pre><p>To replicate the run-at-least-once behavior, we need to replicate the code before the loop.<\/p><pre>  n = 0;\r\n  count = 0;\r\n  doStuff();\r\n  for ind = 1:n\r\n      doStuff();\r\n      count = count + 1;\r\n  end<\/pre><h3>Your Style Preferences?<a name=\"9\"><\/a><\/h3>\r\n   <p>I have to say that having lots of code in the body that might have to be replicated is something I would avoid.  So I'd see\r\n      if I could reasonably stick the bulk of the loop body code in another function.  After that, I still have a slight preference\r\n      for one style over the others, but I'd like to hear your thoughts first.\r\n   <\/p>\r\n   <p>Which programming style do you prefer here?  Using <tt>for<\/tt>, <tt>while<\/tt> with an explicit condition, <tt>while<\/tt> with a <tt>break<\/tt>, or do you have an even better code pattern?  Post your thoughts <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=105#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_7ab8bdf07f6f4adf9be6cd0c51232c21() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='7ab8bdf07f6f4adf9be6cd0c51232c21 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 7ab8bdf07f6f4adf9be6cd0c51232c21';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = 'Loren Shure';\r\n        copyright = 'Copyright 2007 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }   \r\n      \r\n-->\r\n<\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_7ab8bdf07f6f4adf9be6cd0c51232c21()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.5<br><\/p>\r\n<\/div>\r\n<!--\r\n7ab8bdf07f6f4adf9be6cd0c51232c21 ##### SOURCE BEGIN #####\r\n%% for Versus while\r\n% A reader suggested I discuss the difference in use of MATLAB's\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/for.html |for|> \r\n% and <https:\/\/www.mathworks.com\/help\/matlab\/ref\/while.html |while|>\r\n% constructs.\r\n%% The Scene\r\n% You want to run some code at least once, regardless of any conditions.\r\n% You might want to run it more often, depending on some conditions.\r\n%% At Least Once in a while\r\n% Here's a couple of solutions using a |while| construct, while ensuring\r\n% the main chunk of code is run at least once, even if the stop condition\r\n% is already met.\r\n%\r\n%    n = 0;\r\n%    i = 1;\r\n%    while true\r\n%         doStuff();\r\n%         if (i > n)\r\n%             break;  \r\n%         end\r\n%         i = i + 1;\r\n%         n = somethingElse();\r\n%    end\r\n%%\r\n% Here's another way that inverts the logic surrounding the condition and\r\n% avoids using an explicit |break| statement.  Instead, it has to check to\r\n% see that |currentState| is still |true|.\r\n%\r\n%    n = 0;\r\n%    i = 1;\r\n%    currentState = true;\r\n%    while currentState\r\n%         doStuff();\r\n%         currentState = (i <= n);\r\n%         if currentState,\r\n%            i = i + 1;\r\n%            n = somethingElse();\r\n%         end\r\n%    end\r\n%\r\n%%\r\n% I wonder if this version is any better than the first.  It is one line\r\n% longer so |currentState| can be explicitly set.  This might be more\r\n% readable to some of you, and less so to others.\r\n%% Taking Care Using for\r\n% To make sure the code |doStuff| runs at least once, we need to take care\r\n% using a |for|-loop.  The reason for this is that the loop code is \r\n% guaranteed to not run at all if the loop counter variable is empty.  To\r\n% ensure the code runs once, we need to repeat the code outside the loop.\r\n% If the code being run is like this example, encapsulated in another\r\n% function, then it's not so difficult to be sure we've got things right.\r\n\r\n%%\r\n% If instead of a single function, we have several statements to run, then\r\n% we have take care to copy all of the code and ensure that we update both\r\n% sets if we ever have to make some changes.\r\n%\r\n%%\r\n% |doStuff| will never be run with the following code sample.\r\n%\r\n%    n = 0;\r\n%    count = 0;\r\n%    for ind = 1:n\r\n%        doStuff();\r\n%        count = count + 1;\r\n%    end\r\n%\r\n%%\r\n% To replicate the run-at-least-once behavior, we need to replicate the\r\n% code before the loop.\r\n%\r\n%    n = 0;\r\n%    count = 0;\r\n%    doStuff();\r\n%    for ind = 1:n\r\n%        doStuff();\r\n%        count = count + 1;\r\n%    end\r\n% \r\n%% Your Style Preferences?\r\n% I have to say that having lots of code in the body that might have to be\r\n% replicated is something I would avoid.  So I'd see if I could reasonably\r\n% stick the bulk of the loop body code in another function.  After that, I\r\n% still have a slight preference for one style over the others, but I'd\r\n% like to hear your thoughts first.\r\n%%\r\n% Which programming style do you prefer here?  Using |for|, |while| with an\r\n% explicit condition, |while| with a |break|, or do you have an even better\r\n% code pattern?  Post your thoughts\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=105#respond here>.\r\n##### SOURCE END ##### 7ab8bdf07f6f4adf9be6cd0c51232c21\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      A reader suggested I discuss the difference in use of MATLAB's for and while constructs.\r\n      \r\n   \r\n   Contents\r\n   \r\n      \r\n    ... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2007\/08\/29\/for-versus-while\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[14,8],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/105"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=105"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/105\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=105"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=105"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=105"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}