Using row_vector (or vector) to represent a matrix


I have a (hopefully) simple coding question. According to the manual, it is more efficient to declare a matrix as a vector or row_vector.

In my data{} block, I have the following:

data {

int N; //number of observations
int D; //number of attributes, excluding the intercept
row_vector[D] A[N]; // A is a NxD matrix of attributes, excluding the intercept. I declare it as a row_vector here.

Now I want to add a column of ones to A for the intercept.

transformed data {

int DD;
vector[N] ones;
row_vector[DD] X[N]; // dim(X[i]) = 1xDD

ones = rep_vector(1,N);
X = append_col(ones, A);

But the last line, X = append_col(ones, A), gives me an error. I cannot append a vector to a row_vector. Instead, the following for-loop seems to work:

for (n in 1:N)
X[n] = append_col(1, A[n]);

But is it possible to avoid the for-loop?

I doubt it, but worrying about a for loop in C++ that gets executed once is a waste of time.

Arrays of vectors are only more efficient than matrices if you acess the elements of the array as vectors. It’s much more efficient to pack everything into matrix operations if possible. That’s not because our loops are slow, but because we’ve optimized the derivative calculations for matrix operations.

As Ben says, though, you only execute transformed data once, so don’t worry about speed in this case.

The way to do what you’re trying to do is this:

matrix[N, D] A;
matrix[N, D + 1] X = append_col(rep_vector(1, N), A);