| MATLAB Function Reference | ![]() |
Conditionally execute statements
Syntax
Description
If expression1 evaluates as false and expression2 as true, MATLAB executes the one or more commands denoted here as statements2.
A true expression has either a logical true or nonzero value. For nonscalar expressions, (for example, is matrix A less then matrix B), true means that every element of the resulting matrix has a logical true or nonzero value.
Expressions usually involve relational operations such as (count < limit) or isreal(A). Simple expressions can be combined by logical operators (&,|,~) into compound expressions such as: (count < limit) & ((height - offset) >= 0).
See if for more information.
Remarks
else if, with a space between the else and the if, differs from elseif, with no space. The former introduces a new, nested if, which must have a matching end. The latter is used in a linear sequence of conditional statements with only one terminating end.
The two segments shown below produce identical results. Exactly one of the four assignments to x is executed, depending upon the values of the three logical expressions, A, B, and C.
if A if A x = a x = a else elseif B if B x = b x = b elseif C else x = c if C else x = c x = d else end x = d end end end
Examples
Here is an example showing if, else, and elseif.
for m = 1:k for n = 1:k if m == n a(m,n) = 2; elseif abs(m-n) == 2 a(m,n) = 1; else a(m,n) = 0; end end end
See Also
if, else, end, for, while, switch, break, return, relational_operators, logical_operators
| else | end | ![]() |