Conversion of Rcpp::NumericMatrix to Eigen::MatrixXd

161 Views Asked by At

I am facing a very similar issue to these questions:

I am writing an R-package, that uses the RcppEigen library for Matrix arithmetic. My problem is that the project is not compiling because of an error in the conversion of the Rcpp::NumericMatrix input to an Eigen::MatrixXd.

The file looks like this:

#include <map>
#include <Rcpp.h>
...
using namespace Eigen;
...
// [[Rcpp::export]]
Rcpp::List my_function(Rcpp::NumericMatrix input_matrix)
{
    ...
    Map<MatrixXd> GATE_matrixx(Rcpp::as<Map<MatrixXd> >(GATE_matrix));
    ...
}

This gives me the following error:

Myfile.cpp:40:65: required from here C:/Users/User/AppData/Local/Programs/R/R-4.2.2/library/Rcpp/include/Rcpp/internal/Exporter.h:31:31:error: matching function for call to 'Eigen::Map<Eigen::Matrix<double, -1, -1> >::Map(SEXPREC*&) 31 | Exporter( SEXP x ) : t(x) | ^ In file included from C:/Users/User/AppData/Local/Programs/R/R-4.2.2/library/RcppEigen/include/Eigen/Core:19 from C:/Users/User/AppData/Local/Programs/R/R-4.2.2/library/RcppEigen/include/Eigen/SparseCore:11 from C:/Users/User/AppData/Local/Programs/R/R-4.2.2/library/RcppEigen/include/Eigen/Sparse:26 from Myfile.cpp:8

I have also tried to change the line to:

MatrixXd input_matrix_eigen(Rcpp::as\<MatrixXd\>(input_matrix));

This gives me the equivalent error :

Myfile.cpp:40:54: required from here C:/Users/User/AppData/Local/Programs/R/R 4.2.2/library/RcppEigen/include/Eigen/src/Core/Matrix.h:332:31:error: matching function for call to 'Eigen::Matrix<double, -1, -1>::_init1<SEXPREC*>(SEXPREC* const&)

Do you have any ideas? If more information is required to evaluate the issue, just let me know.

1

There are 1 best solutions below

0
On

If you use the command

RcppEigen::RcppEigen.package.skeleton("demoPackage")

an example package demoPackage is created for you which you can install the usual way. It contains example functions to create amd return a matrix:

// [[Rcpp::export]]
Eigen::MatrixXd rcppeigen_hello_world() {
    Eigen::MatrixXd m1 = Eigen::MatrixXd::Identity(3, 3);
    // Eigen::MatrixXd m2 = Eigen::MatrixXd::Random(3, 3);
    // Do not use Random() here to not promote use of a non-R RNG
    Eigen::MatrixXd m2 = Eigen::MatrixXd::Zero(3, 3);
    for (auto i=0; i<m2.rows(); i++)
        for (auto j=0; j<m2.cols(); j++)
            m2(i,j) = R::rnorm(0, 1);

    return m1 + 3 * (m1 + m2);
}

If you set the same seed as I do you should get the same matrix

> set.seed(42)
> demoPackage::rcppeigen_hello_world()
        [,1]      [,2]      [,3]
[1,] 8.11288 -1.694095  1.089385
[2,] 1.89859  5.212805 -0.318374
[3,] 4.53457 -0.283977 10.055271
>