APPLY Function

APPLY (modname, argument1 <, argument2, …, argument14> ) ;

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:

modname

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. The module should return a numeric value.

argument

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 that returns a numeric value. 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 $n$ scalar arguments, argument1 through argumentn should be passed to APPLY where $1 \leq n \leq 14$. 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 accepts either numeric or 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 24.44.

Figure 24.44: Result of a Module Applied to Each Argument in a Matrix

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 24.45.

Figure 24.45: Result of a Module Applied to Each Argument in a Matrix

a
-1 0 1

b
-2 0 2

r
1 0 -1


Although the APPLY function is povided as a convenience, it is usually unnecessary to use it. It is often more effienct to write your functions to take vector, rather than scalar, arguments.