Section 7.1 Relational and Equality Operators
Relational operators are important for making decisions as they allow us to compare values with each other. The following relational and equality operators share their syntax with in C, except for the negation (not) operator which is a tilde symbol
~
in MATLAB (recall that C uses an exclamation mark !
):Operator | Operation |
< |
less than |
> |
greater than |
<= |
less than or equal to |
>= |
greater than or equal to |
== |
equal to |
~= |
not equal to (in C: != ) |
In MATLAB, logical true is 1 and logical false is 0. Recall that in C any value other than 0 is interpreted as true. In fact, MATLAB has a logical data type, and so the result of comparing two quantities is of that datatype:
>> a = 3; >> b = 4; >> a == b
ans = logical 0
>> a < b
ans =
logical
1
If two arrays are compared (must be the same size), the result is an array of logical values from an element-by-element comparison of the two arrays. This is known as a Logical Vector.
Subsection 7.1.1 Logical Vector
A logical vector is the result of a logical comparison with vectors.
When a logical vector is used to access array elements, only those corresponding to the logical true (1) value are selected.
>> arr = [8 -1 2 3 9 -2 -5 -11 8 12];
>> ipos = arr >= 0
ipos =
1×10 logical array
1 0 1 1 1 0 0 0 1 1
>> posv = arr(ipos)
posv =
8 2 3 9 8 12
This is not the same as accessing array elements with an array of numerical 0s and 1s! Take a look at how NOT TO DO THIS:
>> wrong = [1 0 1 1 1 0 0 0 1 1]
wrong =
1 0 1 1 1 0 0 0 1 1
>> arr(wrong)
Array indices must be positive integers or logical values.
Subsection 7.1.2 Logical Operators
There are two types of logical operators in MATLAB: scalar operands (like C) and array operands (which produce logical arrays).
MATLAB | C-Programming | ||
Scalar | Array | Scalar | |
&& |
& |
AND | && |
|| |
| |
OR | || |
~ |
~ |
NOT | ! |
Scalar logical operators work just like in C, operands must be scalar quantities and short-circuit evaluations apply.
If two arrays are compared (must be the same size), the result is an array of logical values from an element-by-element comparison of the two arrays.