The fundamental units in the SAS/IML language are matrices and vectors. Consequently, you might wonder about conditional expression such as if v>0 then.... What does this expression mean when v contains more than a single element?
Evaluating vector expressions
When you test a vector for some condition, expressions like v>0 resolve to matrices of zeros and ones, as shown in the following example:
proc iml; v = {1 2 -1 3 0}; b = (v>0); /* boolean vector of 0s and 1s */ print b; |
The b vector contains a 1 in locations for which the corresponding element of v is greater than zero. (That is, the condition is true.) The b vector contains a 0 in locations for which the corresponding element of v is not greater than zero. (The condition is false.)
In statistical programming you often want to know whether all of the elements of v satisfy the condition. However, sometimes you might be interested in whether any of the elements satisfy the condition. In the SAS/IML language, you can use the ALL function and the ANY function, respectively, to investigate those questions. The following statements call the ALL and ANY functions:
allV = all(v>0); anyV = any(v>0); print allV anyV; |
The value of allV is 0, which indicates that the condition is false: not all of the elements of v are greater than zero. The value of anyV is 1, which indicates that the condition is true: at least one element of v is greater than zero.
Testing vector expressions
Most of the time, statistical programmers are interested in whether a condition holds for each and every element of a vector or matrix. Consequently, the IF-THEN/ELSE statement tests whether all elements satisfy the condition. That is, the expression if v>0 then... is equivalent to the expression if all(v>0) then.... This is shown in the following example:
/* the IF statement tests uses an implicit ALL */ if v > 0 then print "ALL v > 0"; else print "For some i, v[i] <= 0"; |
This implies that you have to explicitly call the ANY function when you want to test whether any element satisfies some criterion. For example, the following statements test whether any element of a vector is not equal to 1:
w = {1 1 2 1}; if any(w ^= 1) then print "For some i, w[i] ^= 1"; else print "ALL w = 1"; |
The ANY and ALL functions are discussed in Section 2.8.1 of my book, Statistical Programming with SAS/IML Software. This chapter is available as a FREE download from the book's Web site.