Using Stan functions on Eigen::Map

Stan functions work on Eigen::Matrix but not on Eigen::Map. The error occurs for examplew ith elt_multiply, with the following message:

/stan/math/prim/mat/fun/elt_multiply.hpp:25:1: note: candidate template
      ignored: could not match 'Matrix' against 'Map'
elt_multiply(const Eigen::Matrix<T1, R, C>& m1,

But in some cases, it could be handy to use Stan functions directly on Map. Is there a good workaround this, that doesn’t involve creating a new Matrix – and essentially duplicating the object?

Edit: how expensive is it actually to duplicate a matrix?

To my knowledge the answer is no. You would have to make the Eigen arguments into templates to allow to pass in matrices or maps. The Eigen help has some doc on this.

I see. Right now, I switched to using Eigen’s functions since I’m working with doubles. At least for the moment, that’s a good solution.

The thing to read is this confusing doc from Eigen on function argument types. The short answer is that many of our functions could be improved by generalizing their function types. We’re happy to take PRs on this one function at a time.


It just needs to allocate and then walk over all the elements. The main downside is increased memory pressure on cache and the potential fragmentation from allocating all these RAII objects like Eigen matrix and standard vector. So it’s going to be expensive compared to an operation like elt_multiply but cheap compared to Cholesky decomposition or even matrix multiplication.

1 Like