{"id":469,"date":"2012-06-15T20:32:39","date_gmt":"2012-06-16T01:32:39","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=469"},"modified":"2016-08-04T08:55:32","modified_gmt":"2016-08-04T13:55:32","slug":"whats-if-all-about","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2012\/06\/15\/whats-if-all-about\/","title":{"rendered":"What&#8217;s &#8220;if&#8221; &#8220;all&#8221; about?"},"content":{"rendered":"<!DOCTYPE html\r\n  PUBLIC \"-\/\/W3C\/\/DTD HTML 4.01 Transitional\/\/EN\">\r\n<style type=\"text\/css\">\r\n\r\nh1 { font-size:18pt; }\r\nh2.titlebg { font-size:13pt; }\r\nh3 { color:#4A4F55; padding:0px; margin:5px 0px 5px; font-family:Arial, Helvetica, sans-serif; font-size:11pt; font-weight:bold; line-height:140%; border-bottom:1px solid #d6d4d4; display:block; }\r\nh4 { color:#4A4F55; padding:0px; margin:0px 0px 5px; font-family:Arial, Helvetica, sans-serif; font-size:10pt; font-weight:bold; line-height:140%; border-bottom:1px solid #d6d4d4; display:block; }\r\n   \r\np { padding:0px; margin:0px 0px 20px; }\r\nimg { padding:0px; margin:0px 0px 20px; border:none; }\r\np img, pre img, tt img, li img { margin-bottom:0px; } \r\n\r\nul { padding:0px; margin:0px 0px 20px 23px; list-style:square; }\r\nul li { padding:0px; margin:0px 0px 7px 0px; background:none; }\r\nul li ul { padding:5px 0px 0px; margin:0px 0px 7px 23px; }\r\nul li ol li { list-style:decimal; }\r\nol { padding:0px; margin:0px 0px 20px 0px; list-style:decimal; }\r\nol li { padding:0px; margin:0px 0px 7px 23px; list-style-type:decimal; }\r\nol li ol { padding:5px 0px 0px; margin:0px 0px 7px 0px; }\r\nol li ol li { list-style-type:lower-alpha; }\r\nol li ul { padding-top:7px; }\r\nol li ul li { list-style:square; }\r\n\r\npre, tt, code { font-size:12px; }\r\npre { margin:0px 0px 20px; }\r\npre.error { color:red; }\r\npre.codeinput { padding:10px; border:1px solid #d3d3d3; background:#f7f7f7; }\r\npre.codeoutput { padding:10px 11px; margin:0px 0px 20px; color:#4c4c4c; }\r\n\r\n@media print { pre.codeinput, pre.codeoutput { word-wrap:break-word; width:100%; } }\r\n\r\nspan.keyword { color:#0000FF }\r\nspan.comment { color:#228B22 }\r\nspan.string { color:#A020F0 }\r\nspan.untermstring { color:#B20000 }\r\nspan.syscmd { color:#B28C00 }\r\n\r\n.footer { width:auto; padding:10px 0px; margin:25px 0px 0px; border-top:1px dotted #878787; font-size:0.8em; line-height:140%; font-style:italic; color:#878787; text-align:left; float:none; }\r\n.footer p { margin:0px; }\r\n\r\n  <\/style><div class=\"content\"><!--introduction--><p>I recently posted about a GOTCHA with the expression <tt>a &lt; x &lt; b<\/tt> in MATLAB and <a href=\"https:\/\/blogs.mathworks.com\/loren\/2012\/05\/14\/why-is-answer-to-3-a-7-unexpected\/#comment-33056\">Matt's<\/a> comments made me look to see if I had ever devoted a post to the behavior of <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/all.html\"><tt>all<\/tt><\/a> (or its companion <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/any.html\"><tt>any<\/tt><\/a>).  So today I will explain how <tt>all<\/tt> works and why you need to take care when you use arrays for testing conditions in <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/if.html\"><tt>if<\/tt><\/a> and <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/while.html\"><tt>while<\/tt><\/a> statements.  This is especially true if you do <b>not<\/b> use them with functions such as <tt>any<\/tt> or <tt>all<\/tt> since they can reduce expressions to scalar <tt>true<\/tt> and <tt>false<\/tt> values.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#0d8b1387-c0d6-4e80-8939-a0527da94726\">Misconception<\/a><\/li><li><a href=\"#4915e902-37f0-496a-85c5-6e98be6f0d0d\">Behavior of Conditional Statements with Array Input<\/a><\/li><li><a href=\"#6d85e5dc-1427-46fb-950b-952d8e7a9654\">Illustration of the Issue<\/a><\/li><li><a href=\"#1824c937-ffe6-427e-800b-697d93984c72\">One Working Way (for loop)<\/a><\/li><li><a href=\"#dbec0fee-c189-45cf-a9a9-36ae0b4a3400\">Another Way for This Simple Problem<\/a><\/li><li><a href=\"#9cd138a1-2fc2-499b-b345-b81611031bcd\">Other Relevant Blogs<\/a><\/li><li><a href=\"#8390ba44-5045-44e3-9550-04ba8076d29a\">Have You Tripped on Arrays with \"if\" or \"while\" Statements?<\/a><\/li><\/ul><\/div><h4>Misconception<a name=\"0d8b1387-c0d6-4e80-8939-a0527da94726\"><\/a><\/h4><p>Sometimes I see code that was written assuming the expression for an <tt>if<\/tt> statement will be a scalar.  It's possible to then be confused if the expression is an array.  If you were to loop through each element in the expression (for example, by placing the <tt>if<\/tt> statement inside a for loop), then each element would be evaluated separately and the expression would only execute the statements contained in the <tt>if<\/tt> portion for nonzero (or <tt>true<\/tt>) expression elements.  However, once you hand the array over as an entity to <tt>if<\/tt>, you should be aware that <b>ALL<\/b> elements must be <tt>true<\/tt> for the expression to be <tt>true<\/tt>, and for the <tt>if<\/tt> body statements to execute.<\/p><p>It's also possible that users think that the statements contained within the body of the <tt>if<\/tt> statement will only be executed for elements that were true in the expression controlling the <tt>if<\/tt> statement.  This is also not true.<\/p><h4>Behavior of Conditional Statements with Array Input<a name=\"4915e902-37f0-496a-85c5-6e98be6f0d0d\"><\/a><\/h4><p>The important thing you need to know is this, quoted from the MATLAB documentation.<\/p><p><b>\"An evaluated expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false.\"<\/b><\/p><p>This means that for an expression to trigger the execution of the body of an <tt>if<\/tt> statement, <tt>all<\/tt> of the elements in the expression be <tt>true<\/tt>.  The following two code segments therefore give the same results.<\/p><pre>          if A &gt; 0\r\n             doSomething\r\n          end<\/pre><pre>          if all(A(:) &gt; 0)\r\n             doSomething\r\n          end<\/pre><h4>Illustration of the Issue<a name=\"6d85e5dc-1427-46fb-950b-952d8e7a9654\"><\/a><\/h4><p>I will first show code that does not work on only the \"relevant\" elements of the <tt>if<\/tt> expression, and then show two ways to achieve the desired result.<\/p><p>Create an input array with integers between 0 and some maximum value.<\/p><pre class=\"codeinput\">intData = randperm(8); intData(randperm(8) &gt; 5) = 0\r\n<\/pre><pre class=\"codeoutput\">intData =\r\n     7     0     3     0     5     0     1     2\r\n<\/pre><p>Start with an output array of constant values, the same size as the input array.<\/p><pre class=\"codeinput\">outDataVec = 42*ones(size(intData));\r\n<\/pre><p>Try replacing output values with 17 where the input array is nonzero.<\/p><pre class=\"codeinput\"><span class=\"keyword\">if<\/span> intData\r\n    outDataVec = 17;\r\n<span class=\"keyword\">end<\/span>\r\noutDataVec\r\n<\/pre><pre class=\"codeoutput\">outDataVec =\r\n    42    42    42    42    42    42    42    42\r\n<\/pre><p>This didn't change my output since the expression isn't true!  Since that didn't work, let's try another way.<\/p><pre class=\"codeinput\">outDataVec1 = 42*ones(size(intData));\r\n<span class=\"keyword\">if<\/span> intData\r\n    outDataVec1(:) = 17; <span class=\"comment\">% see if we can just replace the \"selected\" elements<\/span>\r\n<span class=\"keyword\">end<\/span>\r\noutDataVec1\r\n<\/pre><pre class=\"codeoutput\">outDataVec1 =\r\n    42    42    42    42    42    42    42    42\r\n<\/pre><p>That didn't work either, since <tt>X(:)<\/tt> simply turns the array <tt>X<\/tt> into a column vector.  And the input expression is still not all true.<\/p><h4>One Working Way (for loop)<a name=\"1824c937-ffe6-427e-800b-697d93984c72\"><\/a><\/h4><pre class=\"codeinput\">outDataFor = 42*ones(size(intData));\r\n<span class=\"keyword\">for<\/span> ind = 1:length(intData)\r\n    <span class=\"keyword\">if<\/span> intData(ind)\r\n        outDataFor(ind) = 17;\r\n    <span class=\"keyword\">end<\/span>\r\n<span class=\"keyword\">end<\/span>\r\noutDataFor\r\n<\/pre><pre class=\"codeoutput\">outDataFor =\r\n    17    42    17    42    17    42    17    17\r\n<\/pre><h4>Another Way for This Simple Problem<a name=\"dbec0fee-c189-45cf-a9a9-36ae0b4a3400\"><\/a><\/h4><p>Of course, there's another better way to calculate the output represented by <tt>outDataFor<\/tt>, in a vectorized way, using logical indexing.<\/p><pre class=\"codeinput\">outDataArray = 42*ones(size(intData));\r\noutDataArray(intData &gt; 0) = 17\r\n<\/pre><pre class=\"codeoutput\">outDataArray =\r\n    17    42    17    42    17    42    17    17\r\n<\/pre><p>Just to show that the <tt>for<\/tt> loop calculation matches the one using logical indexing.<\/p><pre class=\"codeinput\">isequal(outDataFor, outDataArray)\r\n<\/pre><pre class=\"codeoutput\">ans =\r\n     1\r\n<\/pre><h4>Other Relevant Blogs<a name=\"9cd138a1-2fc2-499b-b345-b81611031bcd\"><\/a><\/h4><p>Here are a couple of links to other posts that cover issues related to these topics.<\/p><div><ul><li><a href=\"https:\/\/blogs.mathworks.com\/loren\/2011\/09\/23\/another-possible-surprise-ignored-nan-values\/\">Another Possible Surprise &#8211; Ignored NaN Values<\/a><\/li><li><a href=\"https:\/\/blogs.mathworks.com\/loren\/2009\/11\/12\/empty-arrays-with-flow-of-control-and-logical-operators\/\">Empty Arrays with Flow of Control and Logical Operators<\/a><\/li><\/ul><\/div><h4>Have You Tripped on Arrays with \"if\" or \"while\" Statements?<a name=\"8390ba44-5045-44e3-9550-04ba8076d29a\"><\/a><\/h4><p>Has the expression for an <tt>if<\/tt> or <tt>while<\/tt> statement bitten you?  How did you figure it out and what did you do to resolve it? <\/p><script language=\"JavaScript\"> <!-- \r\n    function grabCode_3d78f44bfad44f8d93447e32e60c64b7() {\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='3d78f44bfad44f8d93447e32e60c64b7 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 3d78f44bfad44f8d93447e32e60c64b7';\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        copyright = 'Copyright 2012 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 copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\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     --> <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_3d78f44bfad44f8d93447e32e60c64b7()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.14<br><\/p><p class=\"footer\"><br>\r\n      Published with MATLAB&reg; 7.14<br><\/p><\/div><!--\r\n3d78f44bfad44f8d93447e32e60c64b7 ##### SOURCE BEGIN #####\r\n%% What's \"if\" \"all\" about?\r\n% I recently posted about a GOTCHA with the expression |a < x < b| in\r\n% MATLAB and\r\n% <https:\/\/blogs.mathworks.com\/loren\/2012\/05\/14\/why-is-answer-to-3-a-7-unexpected\/#comment-33056\r\n% Matt's> comments made me look to see if I had ever devoted a post to the\r\n% behavior of\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/all.html\r\n% |all|> (or its companion\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/any.html\r\n% |any|>).  So today I will explain how |all| works and why you need to\r\n% take care when you use arrays for testing conditions in\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/if.html |if|>\r\n% and <https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/while.html\r\n% |while|> statements.  This is especially true if you do *not* use them\r\n% with functions such as |any| or |all| since they can reduce expressions\r\n% to scalar |true| and |false| values.\r\n\r\n%% Misconception\r\n% Sometimes I see code that was written assuming the expression for an |if|\r\n% statement will be a scalar.  It's possible to then be confused if the\r\n% expression is an array.  If you were to loop through each element in the\r\n% expression (for example, by placing the |if| statement inside a for\r\n% loop), then each element would be evaluated separately and the expression\r\n% would only execute the statements contained in the |if| portion for\r\n% nonzero (or |true|) expression elements.  However, once you hand the\r\n% array over as an entity to |if|, you should be aware that *ALL* elements\r\n% must be |true| for the expression to be |true|, and for the |if| body\r\n% statements to execute.\r\n%\r\n% It's also possible that users think that the statements contained within\r\n% the body of the |if| statement will only be executed for elements that\r\n% were true in the expression controlling the |if| statement.  This is also\r\n% not true.\r\n%\r\n%% Behavior of Conditional Statements with Array Input\r\n% The important thing you need to know is this, quoted from the MATLAB\r\n% documentation.\r\n%%\r\n% *\"An evaluated expression is true when the result is nonempty and contains\r\n% all nonzero elements (logical or real numeric). Otherwise, the expression\r\n% is false.\"*\r\n\r\n%%\r\n% This means that for an expression to trigger the execution of the body\r\n% of an |if| statement, |all| of the elements in the expression be\r\n% |true|.  The following two code segments therefore give the same results.\r\n%\r\n%            if A > 0\r\n%               doSomething\r\n%            end\r\n%\r\n%\r\n%            if all(A(:) > 0)\r\n%               doSomething\r\n%            end\r\n%\r\n%% Illustration of the Issue\r\n% I will first show code that does not work on only the \"relevant\" elements\r\n% of the |if| expression, and then show two ways to achieve the desired\r\n% result.\r\n%\r\n% Create an input array with integers between 0 and some maximum value.\r\nintData = randperm(8); intData(randperm(8) > 5) = 0\r\n%%\r\n% Start with an output array of constant values, the same size as the input\r\n% array.\r\noutDataVec = 42*ones(size(intData));\r\n%%\r\n% Try replacing output values with 17 where the input array is nonzero.\r\nif intData\r\n    outDataVec = 17;\r\nend\r\noutDataVec\r\n\r\n%% \r\n% This didn't change my output since the expression isn't true!  Since that\r\n% didn't work, let's try another way.\r\noutDataVec1 = 42*ones(size(intData));\r\nif intData\r\n    outDataVec1(:) = 17; % see if we can just replace the \"selected\" elements\r\nend\r\noutDataVec1\r\n%%\r\n% That didn't work either, since |X(:)| simply turns the array |X| into a\r\n% column vector.  And the input expression is still not all true.\r\n%% One Working Way (for loop)\r\noutDataFor = 42*ones(size(intData));\r\nfor ind = 1:length(intData)\r\n    if intData(ind)\r\n        outDataFor(ind) = 17;\r\n    end\r\nend\r\noutDataFor\r\n%% Another Way for This Simple Problem\r\n% Of course, there's another better way to calculate the output represented\r\n% by |outDataFor|, in a vectorized way, using logical indexing.\r\noutDataArray = 42*ones(size(intData));\r\noutDataArray(intData > 0) = 17\r\n%%\r\n% Just to show that the |for| loop calculation matches the one using\r\n% logical indexing.\r\nisequal(outDataFor, outDataArray)\r\n%% Other Relevant Blogs\r\n% Here are a couple of links to other posts that cover issues related to\r\n% these topics.\r\n%\r\n% * <https:\/\/blogs.mathworks.com\/loren\/2011\/09\/23\/another-possible-surprise-ignored-nan-values\/ Another Possible Surprise \u00e2\u20ac\u201c Ignored NaN Values>\r\n% * <https:\/\/blogs.mathworks.com\/loren\/2009\/11\/12\/empty-arrays-with-flow-of-control-and-logical-operators\/ Empty Arrays with Flow of Control and Logical Operators>\r\n% \r\n%% Have You Tripped on Arrays with \"if\" or \"while\" Statements?\r\n% Has the expression for an |if| or |while| statement bitten you?  How did\r\n% you figure it out and what did you do to resolve it?  I'd love to see\r\n% your thoughts <https:\/\/blogs.mathworks.com\/loren\/?p=XXX#respond here>.\r\n##### SOURCE END ##### 3d78f44bfad44f8d93447e32e60c64b7\r\n-->","protected":false},"excerpt":{"rendered":"<!--introduction--><p>I recently posted about a GOTCHA with the expression <tt>a &lt; x &lt; b<\/tt> in MATLAB and <a href=\"https:\/\/blogs.mathworks.com\/loren\/2012\/05\/14\/why-is-answer-to-3-a-7-unexpected\/#comment-33056\">Matt's<\/a> comments made me look to see if I had ever devoted a post to the behavior of <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/all.html\"><tt>all<\/tt><\/a> (or its companion <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/any.html\"><tt>any<\/tt><\/a>).  So today I will explain how <tt>all<\/tt> works and why you need to take care when you use arrays for testing conditions in <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/if.html\"><tt>if<\/tt><\/a> and <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2012a\/techdoc\/ref\/while.html\"><tt>while<\/tt><\/a> statements.  This is especially true if you do <b>not<\/b> use them with functions such as <tt>any<\/tt> or <tt>all<\/tt> since they can reduce expressions to scalar <tt>true<\/tt> and <tt>false<\/tt> values.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2012\/06\/15\/whats-if-all-about\/\">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],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/469"}],"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=469"}],"version-history":[{"count":11,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/469\/revisions"}],"predecessor-version":[{"id":1956,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/469\/revisions\/1956"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=469"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=469"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=469"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}