Multiply matrix by tensor

I am building a model and i need to multiply a beta \times X but i an not sure how to do it.

data {

         matrix[N, K] y; // observations
         matrix[N, P] X[K]; // input variables

parameters {
         matrix[P, K] beta; // X's coefficients

model {

   // sigma_obs was defined before..
   //here is my problem
    y ~ multi_normal_lpmf( beta*X, sigma_obs);


This does not work in stan right now.

You need to write beta as vector[P] beta[K] and then loop over K… you should also write y as vector[N] y[K] .

What exactly the error Stan produces? There may be some issues in the codes.

I guess you want to specify X as a matrix, not an array here. Please double check.

In this segment of the code, the LHS is a matrix, while the RHS requires a vector.

Finally, by the way of specification, beta*X may be not well defined since a matrix beta cannot be multiplied with array X, I guess.


If i do that i will end defining K independent normal distribution and i need to keep the covariance. is there a another way to define it?

Hi the exact error is:

No matches for: 

matrix * matrix[ ]

you should calculate the cholesky factorisation of sigma_obs once and then use it with multi_normal_cholesky_lpdf. This avoids the huge overhead to recompute that over and over.

1 Like

You can use a for loop

for (i in 1:N){
	y[i, ] ~ multi_normal(mu, Sigma);

where mu is something you should be defined based on i.

1 Like