MATLAB Function Reference Previous page   Next Page

Conditionally execute statements



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 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 if for more information.


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.


Here is an example showing if, else, and elseif.

For k=5 you get the matrix

See Also

if, else, end, for, while, switch, break, return, relational operators, logical operators (elementwise and short-circuit)

Previous page  else end Next page

© 1994-2005 The MathWorks, Inc.