# Array of matrices to single matrix by row product

Hi!

If I have a 1 dimensional array A of size t populated with j x i matrices, how can I use the products of the rows of matrices in A to generate a single j x t matrix? For example:

``````matrix[nj,ni] A[nt];
matrix [nj,nt] B; //or perhaps vector[nj] B[nt];

for (t in 1:nt){
for (i in 1:ni){
for (j in 1:nj){
B[j,i] = prod(A[t,j,1:ni]);
}
}
}
``````

I’m really stumped.

Thank you! I love Stan.

Matt

So your first set of matrices (A) has three indexes, j, i, and t.

Your second (B) has the indices j and t.

So if you’re computing the dot product of A and B over one dimension, you’ll lose that dimension. That means you’ll lose either dimension j or t, which means that the result isn’t going to have the dimensions j and t.

Does that help at all? I think either B needs to be shaped differently or the output has different dimensions. You can do dimensionality checks like above to try to get things in the right order.

2 Likes

@Buzz Just so we’re clear on what you’re trying to do, let’s make the dimensions concrete. Suppose `A` contains two 3x4 matrices:

``````matrix[3,4] A; // so A and A are both 3x4 matrices
``````

It sounds like you want a new matrix `B` that has dimensions `3x2`

``````matrix[3,2] B;
``````

where

``````B[1,1] = prod(A[1,1:4])
B[2,1] = prod(A[2,1:4])
B[3,1] = prod(A[3,1:4])
B[1,2] = prod(A[1,1:4])
B[2,2] = prod(A[2,1:4])
B[3,2] = prod(A[3,1:4])
``````

Is that right?

I’m not sure that’s what you want, but if it is then I think you don’t need the loop over `ni`, just over `nt` and `nj`. Something like this:

``````for (t in 1:nt){   // or 1:cols(B)
for (j in 1:nj){ // or 1:rows(B)
B[j,t] = prod(A[t,j, ]);
}
}
``````

But maybe I’m not understanding.

1 Like

Thanks, Jonah. Yes, that is exactly what I would like to perform.

Thanks, again, and kindest regards,
Matt

1 Like

Thanks, Ben!

I also must apologize–in my original post I had “B[j,i] = prod…” where I I really should have said B[j,t].

Great catch, Jonah.