3.1 Vectorization of Real-Valued Functions

Although listed in this chapter, many of Stan’s built-in functions are vectorized so that they may be applied to any argument type. The vectorized form of these functions is not any faster than writing an explicit loop that iterates over the elements applying the function—it’s just easier to read and write and less error prone.

3.1.1 Unary Function Vectorization

Many of Stan’s unary functions can be applied to any argument type. For example, the exponential function, exp, can be applied to real arguments or arrays of real arguments. Other than for integer arguments, the result type is the same as the argument type, including dimensionality and size. Integer arguments are first promoted to real values, but the result will still have the same dimensionality and size as the argument. Real and real array arguments

When applied to a simple real value, the result is a real value. When applied to arrays, vectorized functions like exp() are defined elementwise. For example,

 // declare some variables for arguments
 real x0;
 real x1[5];
 real x2[4, 7];
 // declare some variables for results
 real y0;
 real y1[5];
 real y2[4, 7];
 // calculate and assign results
 y0 = exp(x0);
 y1 = exp(x1);
 y2 = exp(x2);

When exp is applied to an array, it applies elementwise. For example, the statement above,

 y2 = exp(x2);

produces the same result for y2 as the explicit loop

 for (i in 1:4)
   for (j in 1:7)
     y2[i, j] = exp(x2[i, j]); Vector and matrix arguments

Vectorized functions also apply elementwise to vectors and matrices. For example,

 vector[5] xv;
 row_vector[7] xrv;
 matrix[10, 20] xm;
 vector[5] yv;
 row_vector[7] yrv;
 matrix[10, 20] ym;
 yv = exp(xv);
 yrv = exp(xrv);
 ym = exp(xm);

Arrays of vectors and matrices work the same way. For example,

 matrix[17, 93] u[12];
 matrix[17, 93] z[12];
 z = exp(u);

After this has been executed, z[i, j, k] will be equal to exp(u[i, j, k]). Integer and integer array arguments

Integer arguments are promoted to real values in vectorized unary functions. Thus if n is of type int, exp(n) is of type real. Arrays work the same way, so that if n2 is a one dimensional array of integers, then exp(n2) will be a one-dimensional array of reals with the same number of elements as n2. For example,

 int n1[23];
 real z1[23];
 z1 = exp(n1);

It would be illegal to try to assign exp(n1) to an array of integers; the return type is a real array.