{"id":46,"date":"2006-07-19T12:49:31","date_gmt":"2006-07-19T17:49:31","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=46"},"modified":"2007-01-02T07:42:09","modified_gmt":"2007-01-02T12:42:09","slug":"how-for-works","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2006\/07\/19\/how-for-works\/","title":{"rendered":"How for Works"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p><a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=45\">Last week<\/a> I touched on the difference between using <tt>1:N<\/tt> and <tt>[1:N]<\/tt> as the expression in a <tt>for<\/tt> statement. I have gotten enough more questions recently on how <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/for.html\"><tt>for<\/tt><\/a> works in MATLAB that it seems time for its own post.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">\"Typical Usage\"<\/a><\/li>\r\n         <li><a href=\"#2\">for Expression Can Be a Matrix<\/a><\/li>\r\n         <li><a href=\"#4\">for Expression can go to Infinity!<\/a><\/li>\r\n         <li><a href=\"#5\">for Scope<\/a><\/li>\r\n         <li><a href=\"#9\">Uses of for<\/a><\/li>\r\n         <li><a href=\"#10\">for Gotcha<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>\"Typical Usage\"<a name=\"1\"><\/a><\/h3>\r\n   <p>The most common use of <tt>for<\/tt> is when we want to do something a certain known number of times and we decide to not vectorize the code.  In this context,\r\n      we often know the total number of times, <tt>N<\/tt> and can write code like this:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">N = 3;\r\n<span style=\"color: #0000FF\">for<\/span> ind = 1:N\r\n    disp(ind)\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><pre style=\"font-style:oblique\">     1\r\n\r\n     2\r\n\r\n     3\r\n\r\n<\/pre><h3>for Expression Can Be a Matrix<a name=\"2\"><\/a><\/h3>\r\n   <p>The <tt>for<\/tt> loop uses each column of the expression as the temporary loop variable.  When MATLAB was designed, <a href=\"https:\/\/www.mathworks.com\/company\/aboutus\/founders\/clevemoler.html\">Cleve<\/a> tells me, he chose <tt>:<\/tt> to create row vectors since <tt>1:N<\/tt> is a natural expression and he expected <tt>:<\/tt> to be involved frequently in setting up loops.\r\n   <\/p>\r\n   <p>From the early days of MATLAB, we could also use a matrix (and these days an N-dimensional array) as the loop expression.\r\n      In these cases, MATLAB iterates on the columns (collapsing all dimensions &gt;1 to be virtual columns).\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">A = reshape(1:6,3,2);\r\ncount = 0;\r\n<span style=\"color: #228B22\">% display loop counter and transpose of loop expression<\/span>\r\n<span style=\"color: #0000FF\">for<\/span> ind = A\r\n    count = count+1;\r\n    disp([count, ind'])\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><pre style=\"font-style:oblique\">     1     1     2     3\r\n\r\n     2     4     5     6\r\n\r\n<\/pre><h3>for Expression can go to Infinity!<a name=\"4\"><\/a><\/h3>\r\n   <p>For the benefit of those who didn't read last week's post, I repeat an interesting MATLAB tidbit.  You can have your <tt>for<\/tt> loop go to <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/inf.html\">Infinity<\/a> in MATLAB if you don't insist on precalculating the vector to iterate over.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #0000FF\">for<\/span> ind = 1:Inf\r\n    disp(ind)\r\n    <span style=\"color: #0000FF\">if<\/span> ind&gt;=2\r\n        disp(<span style=\"color: #A020F0\">'Stopping now'<\/span>)\r\n        <span style=\"color: #0000FF\">break<\/span>\r\n    <span style=\"color: #0000FF\">end<\/span>\r\n<span style=\"color: #0000FF\">end<\/span>\r\nind<\/pre><pre style=\"font-style:oblique\">     1\r\n\r\n     2\r\n\r\nStopping now\r\n\r\nind =\r\n\r\n     2\r\n\r\n<\/pre><h3>for Scope<a name=\"5\"><\/a><\/h3>\r\n   <p>The scope of the loop counter in MATLAB's <tt>for<\/tt> loop is not like other laguages as far as I know.  You can reassign values to the counter inside the loop and yet the loop\r\n      will, in certain ways, proceed as if that reassignment hadn't happened.  Let's look at some examples.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #0000FF\">for<\/span> ind = 1:3\r\n    disp(ind)\r\n<span style=\"color: #0000FF\">end<\/span>\r\nind<\/pre><pre style=\"font-style:oblique\">     1\r\n\r\n     2\r\n\r\n     3\r\n\r\n\r\nind =\r\n\r\n     3\r\n\r\n<\/pre><p>In this case, we don't try any funny business and we see we can use the final value of <tt>ind<\/tt> past the end of the <tt>for<\/tt> loop.  This was true as well for the case in which we had the loop counter go to <tt>Inf<\/tt>.\r\n   <\/p>\r\n   <p>MATLAB will continue marching through the loop even if, inside, the loop variable gets disturbed, unless you do something\r\n      like above and <tt>break<\/tt> out when a condition is met (or, of course, if there's an error).  Watch this example:\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #0000FF\">for<\/span> ind = 1:3\r\n    ind\r\n    ind = 10\r\n<span style=\"color: #0000FF\">end<\/span>\r\nind<\/pre><pre style=\"font-style:oblique\">\r\nind =\r\n\r\n     1\r\n\r\n\r\nind =\r\n\r\n    10\r\n\r\n\r\nind =\r\n\r\n     2\r\n\r\n\r\nind =\r\n\r\n    10\r\n\r\n\r\nind =\r\n\r\n     3\r\n\r\n\r\nind =\r\n\r\n    10\r\n\r\n\r\nind =\r\n\r\n    10\r\n\r\n<\/pre><p>I reset <tt>ind<\/tt> inside the loop, and yet when the loop continues on its next pass, it reverts to using the loop expression to determine whether\r\n      or not the <tt>for<\/tt> loop is complete.\r\n   <\/p>\r\n   <h3>Uses of for<a name=\"9\"><\/a><\/h3>\r\n   <p>With the introduction of the JIT\/Accelerator in MATLAB 6.5, <tt>for<\/tt> loops often do not exact a large performance penalty as they had in the past. I can think of situations in which using <tt>for<\/tt> makes lots of sense, even though MATLAB is a vector-oriented language.\r\n   <\/p>\r\n   <div>\r\n      <ul>\r\n         <li>code can't be vectorized<\/li>\r\n         <li>takes too much memory if vectorized<\/li>\r\n         <li>code with loop is clearer and more maintainable<\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>for Gotcha<a name=\"10\"><\/a><\/h3>\r\n   <p>The main blunder people make using <tt>for<\/tt> loops is assigning output to an array that is not preallocated before the loop begins.  This results in MATLAB constantly\r\n      needing to reallocate memory for an array that is typically one element larger each time through the loop.  If you're not\r\n      careful, this memory allocation time can overwhelm the time of the calculation.  One pattern I have seen that doesn't flagrantly\r\n      preallocate the output (but does intrinsically) is when you have the loop go in reverse.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">N = 7;\r\n<span style=\"color: #0000FF\">for<\/span> ind = N:-1:1\r\n    B(ind) = ind\r\n    <span style=\"color: #0000FF\">if<\/span> ind &lt;= N-1\r\n        <span style=\"color: #0000FF\">break<\/span>;\r\n    <span style=\"color: #0000FF\">end<\/span>\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><pre style=\"font-style:oblique\">\r\nB =\r\n\r\n     0     0     0     0     0     0     7\r\n\r\n\r\nB =\r\n\r\n     0     0     0     0     0     6     7\r\n\r\n<\/pre><p>When, how, and why do you use <tt>for<\/tt> loops?  Do you know of other perils to watch out for?  Post your thoughts <a href=\"?p=46#respond\">here<\/a>.\r\n   <\/p>\r\n   <p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br>\r\n      Published with MATLAB&reg; 7.2<br><\/p>\r\n<\/div>\r\n<!--\r\n##### SOURCE BEGIN #####\r\n%% How for Works\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=45 Last week> I touched on the\r\n% difference between using |1:N| and |[1:N]| as the expression in a |for|\r\n% statement.\r\n% I have gotten enough more questions recently on how \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/for.html |for|>\r\n% works in MATLAB that it seems time for its own post.   \r\n%% \"Typical Usage\"\r\n% The most common use of |for| is when we want to do something a certain\r\n% known number of times and we decide to not vectorize the code.  In this\r\n% context, we often know the total number of times, |N| and can write code\r\n% like this:\r\nN = 3;\r\nfor ind = 1:N\r\n    disp(ind)\r\nend\r\n%% for Expression Can Be a Matrix\r\n% The |for| loop uses each column of the expression as the temporary\r\n% loop variable.  When MATLAB was designed, \r\n% <https:\/\/www.mathworks.com\/company\/aboutus\/founders\/clevemoler.html Cleve>\r\n% tells me, he chose |:| to create row vectors since |1:N| is a natural \r\n% expression and he expected |:| to be involved frequently in setting up \r\n% loops.  \r\n%%\r\n% From the early days of MATLAB, we could also use a matrix (and these days\r\n% an N-dimensional array) as the loop expression. In these cases, MATLAB\r\n% iterates on the columns (collapsing all dimensions >1 to be virtual\r\n% columns).\r\nA = reshape(1:6,3,2);\r\ncount = 0;\r\n% display loop counter and transpose of loop expression\r\nfor ind = A\r\n    count = count+1;\r\n    disp([count, ind'])  \r\nend\r\n%% for Expression can go to Infinity!\r\n% For the benefit of those who didn't read last week's post, I repeat an\r\n% interesting MATLAB tidbit.  You can have your |for| loop go to \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/inf.html Infinity>\r\n% in MATLAB if you don't insist on precalculating the vector to iterate\r\n% over.\r\nfor ind = 1:Inf\r\n    disp(ind)\r\n    if ind>=2\r\n        disp('Stopping now')\r\n        break\r\n    end\r\nend\r\nind\r\n%% for Scope\r\n% The scope of the loop counter in MATLAB's |for| loop is not like other\r\n% laguages as far as I know.  You can reassign values to the counter inside\r\n% the loop and yet the loop will, in certain ways, proceed as if that\r\n% reassignment hadn't happened.  Let's look at some examples.\r\nfor ind = 1:3\r\n    disp(ind)\r\nend\r\nind\r\n%%\r\n% In this case, we don't try any funny business and we see we can use the\r\n% final value of |ind| past the end of the |for| loop.  This was true as\r\n% well for the case in which we had the loop counter go to |Inf|.\r\n%%\r\n% MATLAB will continue marching through the loop even if, inside, the\r\n% loop variable gets disturbed, unless you do something like above\r\n% and |break| out when a condition is met (or, of course, if there's an\r\n% error).  Watch this example:\r\nfor ind = 1:3\r\n    ind\r\n    ind = 10\r\nend\r\nind\r\n%% \r\n% I reset |ind| inside the loop, and yet when the loop continues on its\r\n% next pass, it reverts to using the loop expression to determine whether\r\n% or not the |for| loop is complete.\r\n%% Uses of for\r\n% With the introduction of the JIT\/Accelerator in MATLAB 6.5, |for| loops\r\n% often do not exact a large performance penalty as they had in the past.\r\n% I can think of situations in which using |for| makes lots of sense, even\r\n% though MATLAB is a vector-oriented language.  \r\n%\r\n% * code can't be vectorized\r\n% * takes too much memory if vectorized\r\n% * code with loop is clearer and more maintainable\r\n%\r\n%% for Gotcha\r\n% The main blunder people make using |for| loops is assigning output to an\r\n% array that is not preallocated before the loop begins.  This results in\r\n% MATLAB constantly needing to reallocate memory for an array that is\r\n% typically one element larger each time through the loop.  If you're not\r\n% careful, this memory allocation time can overwhelm the time of the\r\n% calculation.  One pattern I have seen that doesn't flagrantly preallocate\r\n% the output (but does intrinsically) is when you have the loop go in\r\n% reverse.\r\nN = 7;\r\nfor ind = N:-1:1\r\n    B(ind) = ind\r\n    if ind <= N-1\r\n        break;\r\n    end\r\nend\r\n%%\r\n% When, how, and why do you use |for| loops?  Do you know of other perils\r\n% to watch out for?  Post your thoughts <?p=46#respond here>.\r\n##### SOURCE END #####\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      Last week I touched on the difference between using 1:N and [1:N] as the expression in a for statement. I have gotten enough more questions recently on how for works in MATLAB that it... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2006\/07\/19\/how-for-works\/\">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,7],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/46"}],"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=46"}],"version-history":[{"count":0,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/46\/revisions"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=46"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=46"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=46"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}