6.1: Relational Operators

Physical Modeling in MATLAB · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    6.1: Relational Operators

    Suppose we have three variables, a, b, and c, and we want to check whether they form a Pythagorean triple. We can use the equality operator (==) to compare two values:

    >> a = 3;
    >> b = 4;
    >> c = 5;
    >> a^2 + b^2 == c^2
    
    ans = logical 1

    The result is a logical value, which means it’s either 1, which means “true,” or 0, which means “false.” Here’s an example where the result is false:

    >> c = 6;
    >> a^2 + b^2 == c^2
    ans = logical 0

    It’s a common error to use the assignment operator (=) instead of the equality operator (==). If you do, you get an error:

    >> a^2 + b^2 = c^2
     a^2 + b^2 = c^2
               |
    Error: Incorrect use of '=' operator.
    To assign a value to a variable, use '='.
    To compare values for equality, use '=='.

    The equality operator is one of several relational operators, so called because they test relations between values. For example, x < 10 is true (1) if the value of x is less than 10 or false (0) if otherwise. And x > 0 is true if x is greater than 0.

    The other relational operators are <= for “less or equal,” >= for “greater or equal,” and ~= for “not equal.”


    This page titled 6.1: Relational Operators was last modified on Thu, 17 Nov 2022 18:18:51 GMT and is shared under a CC BY-NC 4.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.