Monday, August 3, 2009

else

Conditionally execute statements

Syntax

  • if expression
    statements1
    else
    statements2
    end

Description

else is used to delineate an alternate block of statements. If expression evaluates as false, 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, "if (matrix A is less than 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 <> or isreal(A). Simple expressions can be combined by logical operators (&,|,~) into compound expressions such as: (count <>= 0).

Examples

In this example, if both of the conditions are not satisfied, then the student fails the course.

  • if ((attendance >= 0.90) & (grade_average >= 60))
    pass = 1;
    else
    fail = 1;
    end;



elseif

Conditionally execute statements

Syntax

  • if expression1
    statements1
    elseif expression2
    statements2
    end

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 <> or isreal(A). Simple expressions can be combined by logical operators (&,|,~) into compound expressions such as: (count <>= 0).

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

For 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 2

No comments:

Post a Comment