| MATLAB® | ![]() |
if expression1, statements1,
elseif expression2, statements2,
end
if expression1, statements1, elseif expression2, statements2, end evaluates expression1 and, if the evaluation yields logical 1 (true) or a nonzero result, executes one or more MATLAB commands denoted here as statements1. If expression1 is false, MATLAB evaluates the elseif expression, expression2. If expression2 evaluates to true or a nonzero result, executes the commands in statements2.
A true expression has either a logical 1 (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 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 Program Control Statements in the MATLAB Programming Fundamentals documentation for more information on controlling the flow of your program code.
The commands else and if, with a space or line break between them, differ from elseif, with no space. The former introduces a new, nested if that requires a matching end statement. 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
endHere 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
endFor k=5 you get the matrix
a =
2 0 1 0 0
0 2 0 1 0
1 0 2 0 1
0 1 0 2 0
0 0 1 0 2if, else, end, for, while, switch, break, return, relational operators, logical operators (elementwise and short-circuit)
![]() | else | enableservice | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |