# How to convert a matrix to an array of vectors?

I’ve got a matrix in my model block:

``````matrix[3,5] x;
``````

Which I need to pass to `cov_exp_quad`, which expects an array of vectors, i.e.:

``````vector[5] x[3];
``````

Is there a simple way to convert it, something like to_vector? If x was in the data block it would be fine, but x results from some linear algebra operations so I think it has to be a matrix.

You have to loop over the rows.

This is pretty similar to what I was asking a few days ago here.

I found that the best way, as @bgoodri suggested, is to use a for-loop to convert one object into another.

So use the matrix variable to perform your linear algebra operations, but then create a new variable (say `x_temp`) and add a for loop to copy each row of `x` to `x_temp`.

We need to have built-ins for this. I created a feature request:

https://github.com/stan-dev/math/issues/669

Related to this, apologies if obvious but wasn’t clear to me from above or the Stan user manual.

Is the following correct?

`vector[N] x[K]` specifies an object `x` which is an array (length `K` ) of vectors (length `N`). And to access the first vector (length `N`) in the array, you can do `x[1, ]`

Yes that is correct. You may be viewing an older version of the manual. The updated version uses the `array` syntax and discusses this 18.4 Multiple indexes with vectors and matrices | Stan User’s Guide.

1 Like

Thank you very much @spinkney!