Problem with vectors

Per the Stan reference manual, (6.10, indexing), a single subscript on a vector should result in a real.
But I get an error from the following function:

functions {
    real ncspline(real x, vector[] beta, vector[] knots);
    real ncspline(real x, vector[] beta, vector[] knots) {
        // Inputs:  x  = a point at which to evaluate the spline
        //          beta = coefficients of each spline basis
        //          knots = the evenly spaced knots of the spline basis
        //   (only the first 2 knots are used: the code assumes the caller
        //    is telling the truth)
        real yhat;   // the predicted value
        int k;   // number of knots
        real delta;  // knot spacing
        real x2;   // temporary variables
	real z ;
	real b ;

        k = size(beta);   // beta is the same length as knots
        x2 = (x- knots[1])/(knots[2] - knots[1]);
      ....

The compiler complains about the x2= line above, with “no matches for vector/ vector”. The phrase “delta = knots[2] - knots[1];” fails as well, with a message that the rhs is a vector.

How do I get a simple scalar out of a vector?

Second note: I found, by chance, that I I have matrix[N,K] x, then x[, 3], used as an argument to a function, is treated as a vector. This makes perfect sense, but is not mentioned as a legal use in the reference manual (that I could see).

Terry T.

It might be that vector[] is actually an array of vectors, so the signature of your function should just have vector for beta and knots.

I think that an array of vectors would be

vector beta[];

Nevertheless, I tried using vector beta, with no brackets, and then size() doesn’t work.

size for vectors was only added in stan 2.26 - if you’re using RStan from CRAN, you will not have access to it. For a vector you will want to use num_elements. The style without the brackets is correct.

This is the correct placement of the brackets for variable declarations in the bodies of programs, but for functions the size is placed after the type when declaring an array. This inconsistency is one of the reasons newer versions of Stan use array[] vector beta

Thank you very much for the suggestions. The program now compiles.

1 Like