Summary: This is a brief tutorial on the logical expressions used in if statements and while loops in MATLAB.
Note: You are viewing an old version of this document. The latest version is available here.
Logical expressions are used in if statements, switch case statements, and while loops to change the sequence of execution of MATLAB commands in response to variable values. A logical expression is one that evaluates to either true or false. For example, v > 0 is a logical expression that will be true if the variable v is greater than zero and false otherwise.
Logical expression are typically formed using the following relational operators:
| Symbol | Relation |
|---|---|
< |
Less than |
<= |
Less than or equal to |
> |
Greater than |
>= |
Greater than or equal to |
== |
Equal to |
~= |
Not equal to |
== is not the same as =; MATLAB's treats them very differently. == compares two values, while = assigns a value to a variable.
Complex logical expressions can be created by combining simpler logical expressions using the following logical operators:
| Symbol | Relation |
|---|---|
~ |
Not |
&& |
And |
|| |
Or |