Programming Statements


Selection Statements

Selection statemements choose one of several control paths in a program. The SAS/IML language supports the IF-THEN and the IF-THEN/ELSE statements. You can use an IF-THEN statement to test an expression and to conditionally perform an operation. You can also optionally specify an ELSE statement. The general form of the IF-THEN/ELSE statement is as follows:

  • IF expression THEN statement1;

  • ELSE statement2;

The expression is evaluated first. If the value of expression is true (which means nonzero and nonmissing), the THEN statement is executed. If the value of expression is false (which means zero or missing), the ELSE statement (if present) is executed. If an ELSE statement is not present, control passes to the next statement in the program.

The expression in an IF-THEN statement is often a comparison, as in the following example:

a = {17 22, 13 10};
if max(a)<20 then
   p = 1;
else p = 0;

The IF clause evaluates the expression max(a)<20. If all values of the matrix a are less than 20, p is set to 1. Otherwise, p is set to 0. For the given values of a, the IF condition is false, since a[1,2] is not less than 20.

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

w = 0;
if n>0 then
   if x>y then w = x;
   else w = y;

There is an ambiguity associated with the previous statements. Is the ELSE statement associated with the first IF-THEN statement or the second? As the indenting indicates, an ELSE statement is associated with the closest previous IF-THEN statement. (If you want the ELSE statement to be associated with the first IF-THEN statement, you need to use a DO group, as described in the next section.)

When the condition to be evaluated is a matrix expression, the result of the evaluation is a temporary matrix of zeros, ones, 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 zero or missing, 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 then

statement;

 

if all(x<y) then

statement;

If you are testing whether at least one element in x is less than the corresponding element in y, use the ANY function , as shown in the following statement:

 

if any(x<y) then

statement;