I'm new to Rcpp and Eigen and I'm trying to run a inplace matrix multiplication while I run into this error. R didn't tell me what the error is about.
SEXP cpp_hom_crit(
const Eigen::Map<Eigen::MatrixXd> Q, Eigen::Map<Eigen::VectorXd> d, Eigen::Map<Eigen::MatrixXd> Qinv) {
Q *= d.asDiagonal() * Qinv; //error happens here
return Rcpp::wrap(Q);
}
I tried this one also, but it does not work either
SEXP cpp_hom_crit(
const Eigen::Map<Eigen::MatrixXd> Q, Eigen::Map<Eigen::VectorXd> d, Eigen::Map<Eigen::MatrixXd> Qinv) {
Q = Q * d.asDiagonal() * Qinv; //error happens here
return Rcpp::wrap(Q);
}
How can I resolve this error and possibly make this faster?
Here is one way to fix your problem. As @chtz alluded to in the comment, you cannot declare a variable
const
and assign to it. So here we assign to a new temporary variable and return that result.Code
Output
The values are of course nonsensical but they illustrate at least the correct dimension. Note that libraries like LAPACK often have dedicated functions for common vector-matrix product expressions, do the looping internally and may also avoid the temporary so not it is not clear that Eigen will automatically be (much) faster.