if

Purpose

Conditionally execute statements.

Synopsis

if expression
    statements 
end
          
if expression1
    statements 
elseif expression2
    statements 
else
    statements 
end

Description

if conditionally executes statements. The simple form is

if expression
    statements
end
The statements execute if the expression has all nonzero elements. The expression is usually the result of

expression rop expression
where rop is one of ==, <, >, <=, >=, or ~=.

More complicated forms use else or elseif. Each if must be paired with a matching end.

Examples

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

for i = 1:n
    for j = 1:n
        if i == j
            a(i,j) = 2;
        elseif abs([i j]) == 1
            a(i,j) = 1;
        else
            a(i,j) = 0;
        end
    end
end

See Also

break, else, end, for, return, while

(c) Copyright 1994 by The MathWorks, Inc.