Equality between two variables/values (==)

There are many times when we need to ask the computer if two variables contain an "equal" value (e.g., x == y), or if one variable contains a value equal to a known constant (e.g., x == 5). Equality is represented in the program using the DOUBLE EQUAL signs operator. The Equality operator (==) should not be confused with the assignment operator.

Equality Test

To test if two variables contain equal values, we use the == notation. Here is an example:

        
        
        x = input('Person 1, give me a number: ');
        y = input('Person 2, give me a number: ');

        if ( x == y )
          fprintf('You both think alike!\n');
        end
        
      

The Assignment Operator.

Assignment is done with the single equals sign. It should never be confused with the equailty test operator: ==

        
        
        x = 5;

        if ( x = 5 ) % WRONG, BAD, NO, STOP. use ==
           ...
        end

        if ( x == 5 ) % CORRECT!
          fprintf(X does contain 5 !\n');
        end
        
      

Back to Topics List