# [Rcpp-devel] list of matrices to Eigen matrices

Dirk Eddelbuettel edd at debian.org
Wed Mar 20 19:16:19 CET 2013

```Mark,

On 20 March 2013 at 13:03, M A wrote:
| 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:

Nope, that is fine. (Apart from maybe doing with *pcv and sticking that into
the ctor directly).  Someone somewhere needs to fill the vector; we don't
have a function for it so you had to fill this in.

| // [[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

No need to be nervous as we get the matrix from R which (presumably) won't
change these internals anytime soo.

| and just pulling out an address). Is there a more direct way of doing
| this?

It looks fine to me.  I'd write very similar code.

Dirk

--
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com
```