Skip to main content
Library homepage
 
Engineering LibreTexts

7.6: Shortcut and, or, Logical Operations

  • Page ID
    84475
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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.

    .


    This page titled 7.6: Shortcut and, or, Logical Operations is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Carey Smith.