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 as follows:

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, as in the following 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 following two statements produce the same result:

 if x<y thenstatement;
   
 if all(x<y) thenstatement;

The following two expressions are valid, but the THEN clause in each case is executed only when all corresponding elements of a and b are unequal:

 if a^=b thenstatement;
   
 if ^(a=b) thenstatement;

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 following expression requires only one element of a and b to be unequal for the expression to be true:

 if any(a^=b) thenstatement;

Previous Page | Next Page | Top of Page