Stan function for vector %*% matrix %*% vector


Let’s say here we have two vectors a(1 by 3), b(3 by 1), and a matrix M (3 by 3), is there an efficient way in stan to do the same job as “a %% M %% b” in R?


Not if a and b differ. If they were the same, you could use quad_form. Just do real foo = a * M * b;.


Thank you. So if

a is an 1 by 3 vector,

b is an 3 by 1 vector,

M is an 3 by 3 matrix,

when we do a * M * b, we will obtain a scalar?




You can also test questions like this yourself by seeing if something like this compiles:

transformed data {
  row_vector[3] y;
  vector[3] z;
  matrix[3, 4] S;
  real ySz = y * S * z; 

A 1 x 3 vector is a row vector of size 3, whereas a 3 x 1 vector is a (column) vector of size 3.

Matrix operations reduce to the simplest type in Stan.