[Rcpp-devel] Returning Armadillo matrices with dimnames

Dirk Eddelbuettel edd at debian.org
Thu May 2 19:53:37 CEST 2013

Hi Sameer,

On 2 May 2013 at 10:16, Sameer D'Costa wrote:
| Hi,
| I am trying to return several Armadillo matrices back to R and to set
| the names for the rows and the columns of each matrix. I have tried
| converting each Armadillo matrix to a NumericMatrix and then setting
| the dimnames on that before returning a list to R. This seems to work
| (see snippet below) however I am not sure if this is the right way to
| go or if I am converting the matrices properly or if extra copies are
| being made. Any advice will be appreciated.

That looks pretty good.  I would simply change to things:

 -- on entry, create an Armadillo matrix "two-step-way" we have been using
    here a lot (and which is used eg in fastLm.cpp): create a NumericMatrix
    from SEXP (no copies), then instantiate arma::mat() using the begin()
    iterator, row, cols and FALSE --- and that way you are sure that only
    pointers to the original memory get copied, and the content itself should

 -- on exit, do the reverse: do you Armadillo calculations, then access the 
    memory behind the arma matrix (also guaranteed to be contiguous) to
    instantiate an Rcpp NumericMatrix.  Then set the attributes as you do
    below and return it.

That should be the most efficient way to go about it while also setting


| library(RcppArmadillo)
| library(inline)
| a <- matrix(c(0.5,0.1,0.1,0.5),nrow=2)
| code <- '
|    arma::mat coeff = Rcpp::as<arma::mat>(a);
|    coeff %= coeff; // some arma calculations
|    Rcpp::CharacterVector names = Rcpp::CharacterVector::create("a", "b");
|    Rcpp::NumericVector rcoeff(wrap(coeff)); // convert to Rcpp?
|    rcoeff.attr("dimnames") = Rcpp::List::create(names, names);
|    return Rcpp::List::create(Rcpp::Named("coeff") =  rcoeff);
|  '
| testfunc  <- cxxfunction(signature(a="numeric"), code,
|                          plugin="RcppArmadillo")
| testfunc(a)
| Thanks in advance.
| Regards
| Sameer
| _______________________________________________
| Rcpp-devel mailing list
| Rcpp-devel at lists.r-forge.r-project.org
| https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

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

More information about the Rcpp-devel mailing list