Create a matrix from a number of vectors (and vice versa)

stanc

#1

I need to create a 3 x 3 matrix out of 3 vectors of dimension 3. These vectors are the output of softmax function.

Is there a simple syntax, something like what numpy does, or do I need to create a loop for this?

Similar question for the reverse process, where I create a vector from rows of a matrix, although, I could avoid doing this by starting with array of vectors.


#2

Loop


#3

Did you check if append_col and append_row work for your problem?


#4

aha, append_row worked.

Not very well though, because you would have to declare a new matrix with a new dimension each step. That’s not very practical. I am back to using a loop.


#5

You definitely don’t want to append in a loop—it will wind up doing a lot of reallocation, turning a linear process into a quadratic one.

Assuming you want to create a stochastic matrix, then it’s just this:

vector[3] a = softmax(...);
vector[3] b = ...;
vector[3] c = ...;
...
matrix[3, 3] abc = [a', b', c'];

That creates a matrix where the a, b, and c are rows. You can also just assign to rows, as

abc[2] = b';

if you’d prefer.

If you want to build out of column vectors, you need to transpose, then transpose back. You can also assign columsn as abc[ , 2] = v if v is a column vector.

We could probably use a variadic append row/append col function.