7.6: Shortcut and, or, Logical Operations
- Page ID
By Carey A. Smith
Consider the following compound logical code:
if ( (n >= 4) & (abs(n) <= 10) )
This will be true for values of n between 4 and 10 inclusive.
You may see code similar to this version:
if ( (n >= 4) && (abs(n) <= 10) )
The "&&" means that if (n >= 4) is false, then MATLAB will skip the check of (abs(n) <= 10), because the compound expression will be false, whether (abs(n) <= 10) is true or false. In this example, it is not necessary to use &&; the & works just fine. "&&" is only needed in a case like this:
if ( (n ~= 0) && (log10(n) <= 0.5) )
because we would want to avoid computing log10(0).
It is similar for | vs. ||
if ( (n < -3) || (x > 2) )
If the 1st logical expression is true, then there is no need to test the 2nd logical expression, because the compound "or" expression is true whenever either part is true. For "or" compound statements, the double "||" is not necessary; you can use the single "|" in all cases.
Tip: for readability, put parentheses around each logical expression, as is shown here. It runs just as fast and avoids both incorrect operations and misunderstandings of the code. Readable code is debuggable code.