[Rcpp-devel] Returning a matrix from RcppEigen

Michael Hannon jmhannon.ucdavis at gmail.com
Fri Jun 27 01:01:13 CEST 2014


Greetings.  I've been trying to get familiar with RcppArmadillo and RcppEigen.
As my "Hello, world!" example I'm using matrix multiplication.  I got the
Armadillo version to work, but I'm having trouble with the Eigen version.

I'm trying to mimic one of Dirk's gallery snippets:

    http://gallery.rcpp.org/articles/eigen-eigenvalues/

I've appended the details.  My problem is that I evidently don't know what to
return from the function.  I've tried various alternatives, but the only one
that compiles is:

    return C;  // C = A * B

This compiles but produces the error message:

    > mat_mul_eigen(amat, bmat)
    Error in eval(expr, envir, enclos) (from srcConn#6) :
        Wrong R type for mapped vector

I must be overlooking something obvious.  Suggestions welcome.  Thanks.

-- Mike

(File is: mat_mul_eigen.cpp.  Executed in R via:
    sourceCpp("./mat_mul_eigen.cpp")
)


#include <RcppEigen.h>

// [[Rcpp::depends(RcppEigen)]]

using Eigen::Map;               // 'maps' rather than copies
using Eigen::MatrixXd;                  // variable size matrix,
double precision
using Eigen::VectorXd;                  // variable size vector,
double precision

// [[Rcpp::export]]

MatrixXd  mat_mul_eigen(Map<MatrixXd> A_,
Map<MatrixXd> B_) {

  MatrixXd C(A_ * B_);

  return C;
}


/*** R

library(microbenchmark)
amat <- matrix(1:9, nrow=3)
bmat <- matrix(10:18, nrow=3)

mat_mul_eigen(amat, bmat)

amat %*% bmat

microbenchmark(
  amat %*% bmat,
  mat_mul_eigen(amat, bmat)
)

*/


More information about the Rcpp-devel mailing list