Description
MATLAB evaluates the
expression
and, if the evaluation yields a logical true or nonzero result, executes one or more MATLAB commands denoted here as
statements
.
When nesting
if
s, each
if
must be paired with a matching
end
.
When using
elseif
and/or
else
within an
if
statement, the general form of the statement is
-
if expression1
statements1
elseif expression2
statements2
statements3
Arguments
expression
expression
is a MATLAB expression, usually consisting of variables or smaller expressions joined by relational operators (
e.g., count < limit),
or logical functions (e.g., isreal(A)
).
Simple expressions can be combined by logical operators (&
,|
,~
) into compound expressions such as the following. MATLAB evaluates compound expressions from left to right, adhering to operator precedence rules.
(count < limit) & ((height - offset) >= 0)
statements
statements
is one or more MATLAB statements to be executed only if the expression
is true
or nonzero.
Remarks
Nonscalar Expressions
If the evaluated expression
yields a nonscalar value, then every element of this value must be true
or nonzero for the entire expression to be considered true
. For example, the statement, if
(A < B)
is true
only if each element of matrix A
is less than its corresponding element in matrix B
. See Example 2, below.
Partial Evaluation of the expression Argument
Within the context of an
if
or while
expression, MATLAB does not necessarily evaluate all parts of a logical expression. In some cases it is possible, and often advantageous, to determine whether an expression is true or false through only partial evaluation.
For example, if A
equals zero in statement 1 below, then the expression evaluates to false
, regardless of the value of B
. In this case, there is no need to evaluate B
and MATLAB does not do so. In statement 2, if A
is nonzero, then the expression is true
, regardless of B
. Again, MATLAB does not evaluate the latter part of the expression.