{"id":61,"date":"2006-11-01T08:27:08","date_gmt":"2006-11-01T13:27:08","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=61"},"modified":"2018-01-08T14:44:26","modified_gmt":"2018-01-08T19:44:26","slug":"a-logical-story","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2006\/11\/01\/a-logical-story\/","title":{"rendered":"A Logical Story"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>Let me set the stage for today's blog. Logical variables have been part of MATLAB from the early days.  They are particularly\r\n         useful in constructs involved flow-of-control, such as <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/if.html\"><tt>if<\/tt><\/a> and <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/while.html\"><tt>while<\/tt><\/a> statements.  But MATLAB, being an array-oriented language, needs to deal with expressions following <tt>if<\/tt> and <tt>while<\/tt> that might be any size, including empty matrices. But sometimes users get confused when two statements, seemingly the same, behave differently.  The understanding lies in\r\n         the intersection of scalar expansion, empty arrays, and logical operators, both <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/logicaloperatorsshortcircuit.html\">short-circuit<\/a> and <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/logical-operations.html\">elementwise<\/a>.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Logical Operators, Scalar Expansion, and Empty Arrays<\/a><\/li>\r\n         <li><a href=\"#5\">Information to Help Unravel the Mystery<\/a><\/li>\r\n         <li><a href=\"#6\">Back to the Example<\/a><\/li>\r\n         <li><a href=\"#10\">Notes and Recommendations<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Logical Operators, Scalar Expansion, and Empty Arrays<a name=\"1\"><\/a><\/h3>\r\n   <p>Recently on the <a>MATLAB newsgroup<\/a>, a user wondered why two statements, that seemed the same, didn't give the same answer.  Let's take a look.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #0000FF\">if<\/span> 4 | []\r\n    disp(<span style=\"color: #A020F0\">'Must be true'<\/span>)\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><pre style=\"font-style:oblique\">Must be true\r\n<\/pre><p>MATLAB evaluates<\/p><pre>            4 | []<\/pre><p>as <tt>true<\/tt>.\r\n   <\/p>\r\n   <p>However, swapping the order of the argument to <tt>|<\/tt> results in a <tt>false<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #0000FF\">if<\/span> [] | 4\r\n    disp(<span style=\"color: #A020F0\">'Must be true'<\/span>)\r\n<span style=\"color: #0000FF\">else<\/span>\r\n    disp(<span style=\"color: #A020F0\">'Must be false'<\/span>)\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><pre style=\"font-style:oblique\">Must be false\r\n<\/pre><p>How can that be?<\/p>\r\n   <h3>Information to Help Unravel the Mystery<a name=\"5\"><\/a><\/h3>\r\n   <p>There are several concepts that might be helpful for understanding this mystery.<\/p>\r\n   <div>\r\n      <ul>\r\n         <li>Empty arrays evaluate to <tt>false<\/tt> for the purposes of <tt>if<\/tt> and <tt>while<\/tt>.\r\n         <\/li>\r\n         <li>The nonscalar <tt>|<\/tt> and <tt>&amp;<\/tt> operators short-circuit in <tt>if<\/tt> and <tt>while<\/tt> expressions, but not otherwise.\r\n         <\/li>\r\n         <li>It's best to feed <tt>if<\/tt> and <tt>while<\/tt> scalar expressions.  This means considering using the newer (MATLAB version 6.5) logical operators <tt>|<\/tt>| and <tt>&amp;&amp;<\/tt>.  These operators <b>always<\/b> short-circuit.\r\n         <\/li>\r\n         <li>Use reduction operations explicitly to reduce expressions to scalar. Examples of these operations include <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/all.html\"><tt>all<\/tt><\/a> and <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/any.html\"><tt>any<\/tt><\/a>.\r\n         <\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Back to the Example<a name=\"6\"><\/a><\/h3>\r\n   <p>So, what's happening with this code?<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #0000FF\">if<\/span> 4 | []\r\n    disp(<span style=\"color: #A020F0\">'Must be true'<\/span>)\r\n<span style=\"color: #0000FF\">end<\/span>\r\n<span style=\"color: #228B22\">% The 4 is nonzero and is unequivocally true, so that's the result you see.<\/span><\/pre><pre style=\"font-style:oblique\">Must be true\r\n<\/pre><p>Inverting the statement requires evaluation of the <tt>[]<\/tt> first, then a scalar expansion occurs with the 4, yielding <tt>[]<\/tt> and that is <tt>false<\/tt>.\r\n   <\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\"><span style=\"color: #0000FF\">if<\/span> [] | 4\r\n    disp(<span style=\"color: #A020F0\">'Must be true'<\/span>)\r\n<span style=\"color: #0000FF\">else<\/span>\r\n    disp(<span style=\"color: #A020F0\">'Must be false'<\/span>)\r\n<span style=\"color: #0000FF\">end<\/span><\/pre><pre style=\"font-style:oblique\">Must be false\r\n<\/pre><p>If you were trying to debug this, however, you'd be tempted to evaluate<\/p><pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">dbg = 4 | []<\/pre><pre style=\"font-style:oblique\">dbg =\r\n     []\r\n<\/pre><p>You would find <tt>dbg<\/tt> is empty (because of scalar expansion) and therefore, would be <tt>false<\/tt> according to most of the rules above.  However, it does not account for the short-circuit nature of <tt>|<\/tt> and <tt>&amp;<\/tt> in the <tt>if<\/tt> and <tt>while<\/tt>.\r\n   <\/p>\r\n   <h3>Notes and Recommendations<a name=\"10\"><\/a><\/h3>\r\n   <p>If you might have empties that you want to check for, check out <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/isempty.html\"><tt>isempty<\/tt><\/a>.\r\n   <\/p>\r\n   <p>Use the <tt>|<\/tt><tt>|<\/tt> and <tt>&amp;&amp;<\/tt> operators in expressions destined for <tt>if<\/tt> and <tt>while<\/tt>.  These expressions behave consistently, meaning they <b>always<\/b> short-circuit, and are therefore easier to debug.  They also force you to reduce your expression to a scalar and it is easier\r\n      to see what a simple <tt>true<\/tt> or <tt>false<\/tt> means in the context of the flow-of-control. Do you have any other guidelines?  Share them <a href=\"https:\/\/blogs.mathworks.com\/loren\/2006\/11\/01\/a-logical-story\/#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\"> \r\n    function grabCode_95f84015251e4f5ea47f434853d1a3e8() {\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='95f84015251e4f5ea47f434853d1a3e8 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 95f84015251e4f5ea47f434853d1a3e8';\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 2006 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      <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_95f84015251e4f5ea47f434853d1a3e8()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code<\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.3<br><\/p>\r\n<\/div>\r\n<!--\r\n95f84015251e4f5ea47f434853d1a3e8 ##### SOURCE BEGIN #####\r\n%% A Logical Story\r\n% Let me set the stage for today's blog. Logical variables have been part\r\n% of MATLAB from the early days.  They are particularly useful in\r\n% constructs involved flow-of-control, such as \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/if.html |if|>\r\n% and \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/while.html |while|>\r\n% statements.  But MATLAB, being an array-oriented language, needs to deal\r\n% with expressions following |if| and |while| that might be any size,\r\n% including\r\n% <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/matlab_prog\/f1-86384.html empty matrices>.\r\n% But sometimes users get confused when two statements, seemingly the same,\r\n% behave differently.  The understanding lies in the intersection of \r\n% <https:\/\/www.mathworks.com\/access\/helpdesk\/help\/techdoc\/learn_matlab\/f2-15099.html scalar expansion>,\r\n% empty arrays, and logical operators, both \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/logicaloperatorsshortcircuit.html short-circuit>\r\n% and <https:\/\/www.mathworks.com\/help\/matlab\/logical-operations.html elementwise>.\r\n%% Logical Operators, Scalar Expansion, and Empty Arrays\r\n% Recently on the \r\n% <http:\/\/.html MATLAB newsgroup>,\r\n% a user wondered why two statements, that seemed the same, didn't give the\r\n% same answer.  Let's take a look.\r\nif 4 | []\r\n    disp('Must be true')\r\nend\r\n%% \r\n% MATLAB evaluates\r\n%\r\n%              4 | [] \r\n%\r\n% as |true|.\r\n%% \r\n% However, swapping the order of the argument to ||| results in a |false|.\r\nif [] | 4\r\n    disp('Must be true')\r\nelse\r\n    disp('Must be false')\r\nend\r\n%% \r\n% How can that be?\r\n%% Information to Help Unravel the Mystery\r\n% There are several concepts that might be helpful for understanding this\r\n% mystery.\r\n%\r\n% * Empty arrays evaluate to |false| for the purposes of |if| and |while|.\r\n% * The nonscalar ||| and |&| operators short-circuit in |if| and |while|\r\n% expressions, but not otherwise.\r\n% * It's best to feed |if| and |while| scalar expressions.  This means\r\n% considering using the newer (MATLAB version 6.5) logical operators |||| and |&&|.  These\r\n% operators *always* short-circuit.\r\n% * Use reduction operations explicitly to reduce expressions to scalar.\r\n% Examples of these operations include \r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/all.html |all|>\r\n% and <https:\/\/www.mathworks.com\/help\/matlab\/ref\/any.html |any|>.\r\n%% Back to the Example\r\n% So, what's happening with this code?\r\nif 4 | []\r\n    disp('Must be true')\r\nend\r\n% The 4 is nonzero and is unequivocally true, so that's the result you see.\r\n%%\r\n% Inverting the statement requires evaluation of the |[]| first, then a\r\n% scalar expansion occurs with the 4, yielding |[]| and that is |false|.\r\nif [] | 4\r\n    disp('Must be true')\r\nelse\r\n    disp('Must be false')\r\nend\r\n%%\r\n% If you were trying to debug this, however, you'd be tempted to evaluate\r\ndbg = 4 | []\r\n%%\r\n% You would find |dbg| is empty (because of scalar expansion) and therefore, would be |false|\r\n% according to most of the rules above.  However, it does not account for\r\n% the short-circuit nature of ||| and |&| in the |if| and |while|.\r\n%% Notes and Recommendations\r\n%\r\n% If you might have empties that you want to check for, check out\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/isempty.html |isempty|>.\r\n%\r\n%%\r\n% Use the |||||| and |&&| operators in expressions destined for |if| and\r\n% |while|.  These expressions behave consistently, meaning they *always*\r\n% short-circuit, and are therefore easier to debug.  They also force you to\r\n% reduce your expression to a scalar and it is easier to see what a simple\r\n% |true| or |false| means in the context of the flow-of-control. Do you\r\n% have any other guidelines?  Share them <?p=61#respond here>.\r\n\r\n##### SOURCE END ##### 95f84015251e4f5ea47f434853d1a3e8\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      Let me set the stage for today's blog. Logical variables have been part of MATLAB from the early days.  They are particularly\r\n         useful in constructs involved flow-of-control,... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2006\/11\/01\/a-logical-story\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[16,15,11],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/61"}],"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=61"}],"version-history":[{"count":2,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/61\/revisions"}],"predecessor-version":[{"id":2530,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/61\/revisions\/2530"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=61"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=61"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=61"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}