Skip to main content

Registration is now open for this year's LibreFest! Join us virtually the week of July 13.

Register here
Engineering LibreTexts

1.11: Logical Operators

  • Page ID
    134910
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \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}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)

    Relational operators allow us to ask one question, such as 'Is x greater than 0?' Logical operators allow us to combine multiple true/false questions into one larger condition. This is extremely useful because real programs often need to check more than one requirement at a time.

    The main logical operators in MATLAB are AND, OR, NOT, and exclusive OR. In MATLAB code, these are written using symbols or functions:

    Operator or function

    Meaning

    Returns true when...

    a & b or and(a,b)

    AND

    both a and b are true

    a | b or or(a,b)

    OR

    a is true, b is true, or both are true

    ~a or not(a)

    NOT

    a is false

    xor(a,b)

    Exclusive OR

    exactly one of a or b is true, but not both

     

    AND (&): returns true only when both conditions are true. If either condition is false, the combined result is false.

     

    Example \(\PageIndex{1}\)

    Suppose a valid quiz score must be between 0 and 10, inclusive. A score is valid only if it satisfies both requirements: it must be greater than or equal to 0, and it must be less than or equal to 10.

    quiz = 8;
    isValid = quiz >= 0 & quiz <= 10
    Solution
    isValid =
    
        logical
    
        1

    If quiz is 8, both conditions are true, so isValid is true. If quiz is -2, the first condition is false. If quiz is 14, the second condition is false. In both cases, the AND expression returns false.

     

    OR (|): returns true when at least one condition is true. OR is useful when more than one option is acceptable.

     

    Example \(\PageIndex{2}\)

    suppose a user may enter either 'y' or 'Y' to answer yes:

    answer = 'Y';
    isYes = answer == 'y' | answer == 'Y'
    Solution
    isYes =
    
      logical
    
       1

    The result is true because one of the two comparisons is true. With OR, both conditions do not need to be true; at least one is enough.

     

     

    NOT (~): reverses a logical value. If something is true, NOT makes it false. If something is false, NOT makes it true.

    Example \(\PageIndex{3}\)

    Using NOT:

    isReady = false;
    notReady = ~isReady
    Solution
    notReady =
    
      logical
    
       1

     

     

    The NOT operator is especially helpful when you want to express the opposite of a condition. For example, if isValid is false, then ~isValid is true.

     

    Exclusive OR (xor): returns true when exactly one of two conditions is true, but not both. This is less common for beginners than AND and OR, but it is useful when two choices are mutually exclusive.

     

    Truth Table

    A truth table is used to list all combinations of logical inputs and their resulting outputs in a table format:

     

    A

    B

    ~A

    A and B

    A or B

    A xor B

    false

    false

    true

    false

    false

    false

    false

    true

    true

    false

    true

    true

    true

    false

    false

    false

    true

    true

    true

    true

    false

    true

    true

    false

     

    Example \(\PageIndex{4}\)

    Truth table examples:

    cold = true;
    night = false;
    condition_1 = cold & night
    condition_2 = cold | night
    condition_3 = ~cold
    condition_4 = xor(cold, night)

    Solution

    condition_1 =
    
    logical
    
    0
    
    
    condition_2 =
    
    logical
    
    1
    
    
    condition_3 =
    
    logical
    
    0
    
    
    condition_4 =
    
    logical
    
    1

     

    Note

    A helpful way to remember the difference between AND and OR is this: AND is stricter because everything must be true. OR is more flexible because only one condition needs to be true.

     

    Combining Relational and Logical Operators

    In engineering calculations, logical operators are often combined with relational operators. This allows us to create conditions that describe acceptable ranges, safety limits, or categories of values.

    Example \(\PageIndex{5}\)

    Combining logical and relational operators. 

    temperature = 104;
    safeTemp = temperature >= 102 & temperature <= 105
    Solution
    safeTemp =
    
    logical
    
    1

    The expression safeTemp in this example reads naturally as: temperature is greater than or equal to 102 AND temperature is less than or equal to 105. Both parts must be true for safeTemp to be true.

     

    Example \(\PageIndex{6}\)

     Combining logical and relational operators. 

    age = 19;
    hasPermit = true;
    canDrive = age >= 18 | hasPermit
    Solution
    canDrive =
    
      logical
    
       1

    This expression says a person can drive if the person is at least 18 OR has a permit. Depending on the situation, OR may or may not be the correct operator. The programmer must choose the operator that matches the meaning of the problem.

     

     

    Short-Circuit Logical Operators

    MATLAB also has short-circuit logical operators: && for AND and || for OR. Short-circuit evaluation means MATLAB may skip checking the second condition if the final result can already be determined from the first condition.

    For example, in an AND expression, if the first condition is false, the final result must be false. MATLAB does not need to check the second condition. In an OR expression, if the first condition is true, the final result must be true, so MATLAB does not need to check the second condition.

     

    Example \(\PageIndex{7}\)

     Using sort-circuit operators. 

    x = -5;
    isPositiveAndSmall = x > 0 && x < 10
    isNegativeOrZero = x < 0 || x == 0
    Solution
    isPositiveAndSmall =
    
      logical
    
       0
    
    
    isNegativeOrZero =
    
      logical
    
       1
    

     

    Note

    Beginner guideline: use && and || when combining single true/false conditions in if statements. Use & and | when working element-by-element with arrays. Later, when we study arrays and logical indexing, this distinction becomes very important.

     

    Precedence Rules for Logical Operators

    Logical expressions also follow precedence rules. Parentheses are evaluated first, then NOT (~), then AND (&), and finally OR (|). Just as with numeric expressions, relying too much on precedence can make code harder to read.

    Order

    Operator

    1

    Parentheses ( )

    2

    NOT ~

    3

    AND &

    4

    OR |

    5

    Left to right for operators of equal precedence

     

    Example \(\PageIndex{8}\)

    Precedence rules. 

    cold = true;
    night = false;
    raining = true;
    
    result1 = cold | night & raining
    result2 = (cold | night) & raining
    Solution
    result1 =
    
        logical
    
        1
    
    
    result2 =
    
        logical
    
        1

    In result1, MATLAB evaluates night & raining first because AND has higher precedence than OR. Then it combines the result with cold using OR. In result2, the parentheses force MATLAB to evaluate cold | night first. These two expressions may produce different results depending on the values of the variables.

     

    Note

    Readability tip: when combining more than two logical conditions, use parentheses even when they are not strictly required. Parentheses make your logic easier to check and reduce the chance of a hidden mistake.

     

    A clear expression is better than a clever expression. For example, the following expression is easy to read:

    isValidDiameter = (diameter > 0) && (diameter <= 10);
    

     

    The parentheses show exactly what two conditions are being combined. This style is especially helpful when your code is read later by classmates, teammates, or your future self.


    1.11: Logical Operators is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by LibreTexts.

    • Was this article helpful?