Chapter Contents Previous Next
 Programming Statements

IF-THEN/ELSE Statements

To perform an operation conditionally, use an IF statement to test an expression. Alternative actions appear in a THEN clause and, optionally, an ELSE statement. The general form of the IF-THEN/ELSE statement is

IF expression THEN statement1 ;
ELSE statement2 ;

The IF expression is evaluated first. If the expression is true, execution flows through the THEN alternative. If the expression is false, the ELSE statement, if present, is executed. Otherwise, the next statement is executed.

The expression to be evaluated is often a comparison, for example,

```   if max(a)<20 then p=0;
else p=1;
```
The IF statement results in the evaluation of the condition (MAX(A)<20). If the largest value found in matrix A is less than 20, P is set to 0. Otherwise, P is set to 1.

You can nest IF statements within the clauses of other IF or ELSE statements. Any number of nesting levels is allowed. The following is an example of nested IF statements:

```   if x=y then
if abs(y)=z then w=-1;
else w=0;
else w=1;
```

When the condition to be evaluated is a matrix expression, the result of the evaluation is a temporary matrix of 0s, 1s, and possibly missing values. If all values of the result matrix are nonzero and nonmissing, the condition is true; if any element in the result matrix is 0, the condition is false. This evaluation is equivalent to using the ALL function.

For example, the statement

 `if x

produces the same result as the statement

 `if all(x

The expressions

 `if a^=b then` statement`;`

and

 `if ^(a=b) then` statement`;`

are valid, but the THEN clause in each case is executed only when all corresponding elements of A and B are unequal.

If you require that only one element in A not be equal to its corresponding element in B, use the ANY function. For example, evaluation of the expression

 `if any(a^=b) then` statement`;`

requires only one element of A and B to be unequal for the expression to be true.

 Chapter Contents Previous Next Top