Search code examples
matrixvectorstanelementwise-operations

Multiply matrix by vector rowwise (sweep)


Does STAN provide a method for multiplying each row of a matrix by a vector, elementwise? i.e. if I had a matrix:

[1,2,3,
 4,5,6]

and a vector:

[2,4,6]

the desired result would be a second matrix:

[2,8,18,
 8,15,36]

I'm sure I can do this as a for loop, but it seems like something I should be able to do without it.


Solution

  • Stan has an elementwise multiplication operator: .*. It applies only to objects of the same type (e.g., two vectors, or two matrices). But we can use the rep_matrix() broadcast function to turn the vector into a matrix:

    my_matrix .* rep_matrix(my_vector', rows(my_matrix))
    

    If the vector is already a row vector in Stan, then the transposition is unnecessary:

    my_matrix .* rep_matrix(my_row_vector, rows(my_matrix))