[Rcpp-devel] list of matrices to Eigen matrices

M A markoilcan at gmail.com
Wed Mar 20 19:03:26 CET 2013


I have a list of matrices in R which I want to turn into a bunch of
Eigen matrices using RcppEigen. I found a way to do this, but it seems
unnecessarily tortured. Here's what I have:


// [[Rcpp::export]]
void listMat(Rcpp::List mat_list) {
    int n_mats = mat_list.size();
    std::vector<Eigen::MatrixXf> vec_of_mats(n_mats);

    for (int i=0; i < n_mats; i++) {
        Rcpp::NumericMatrix tmpcv = mat_list[i];
        double *pcv = &tmpcv(0,0);

        Eigen::Map<Eigen::MatrixXd> tmpmapd(pcv, tmpcv.nrow(), tmpcv.ncol());
        vec_of_mats[i] = Eigen::MatrixXf(tmpmapd.cast<float>());
    }
    std::cout << vec_of_mats[0] << std::endl; // Sanity check.
    return;
}

Note that I'm putting each matrix in my R list into a std::vector
where each element is a float matrix (ie MatrixXf). This does assume
that Rcpp::NumericMatrix stores the matrix data contiguously and in
column-major order, which is true, but will it always necessarily be
so? (I get a little bit nervous about reaching into a class like this
and just pulling out an address). Is there a more direct way of doing
this?

Thanks,
Mark


More information about the Rcpp-devel mailing list