APPLY Function |
The APPLY function applies a user-defined module to each element of the argument matrix or matrices and returns a matrix of results.
The arguments to the APPLY statement are as follows:
specifies the name of an existing function module. You can specify the module name as a literal string or as matrix that contains the module name.
specifies an argument passed to the module. You must have at least one argument. You can specify up to 15 arguments.
The first argument to APPLY is the name of a function module. The module must take scalar arguments and must already be defined before the APPLY function is executed. The subsequent arguments to the APPLY function are the arguments passed to the module. They all must have the same dimension.
If the function module takes scalar arguments, argument1 through argumentn should be passed to APPLY where . The APPLY function calls the module one time for each element in its input arguments. The result has the same dimension as the input arguments, and each element of the result corresponds to the module applied to the corresponding elements of the argument matrices. The APPLY function can work on numeric in addition to character arguments. For example, the following statements define module ABC and then call the APPLY function, with matrix a as an argument:
start abc(x); r = x + 100; return (r); finish abc; a = {6 7 8, 9 10 11}; s = apply("ABC", a); print s;
The result is shown in Figure 23.42.
s | ||
---|---|---|
106 | 107 | 108 |
109 | 110 | 111 |
The module can also alter the contents of the arguments. In the following example, the statements define the module ABSDIFF and call the APPLY function:
/* compute abs(x-y); permute elements of x and y so that x[i] >= y[i] */ start AbsDiff(x, y); if x<y then do; /* swap x and y */ t = x; x = y; y = t; end; return( x-y ); finish; a = {-1 0 1}; b = {-2 0 2}; mod = "AbsDiff"; r = apply(mod, a, b); print a, b, r;
Notice that the third element of the a and b arguments are exchanged, as shown in Figure 23.43.
a | ||
---|---|---|
-1 | 0 | 2 |
b | ||
---|---|---|
-2 | 0 | 1 |
r | ||
---|---|---|
1 | 0 | 1 |