Tuesday, July 15, 2014

R object automatically wrapped in RcppArmadillo

Just discovered a nice feature of RcppArmadillo: when you pass an R vector or matrix into a c++ function that receives an arma::vec or arma::mat, you don't have to do the conversion at all, RcppArmadillo deals with it automatically for you; and when you return the arma::... object in your c++ function, they will be wrapped into the right R objects when they are passed back into R. A demonstration:

// c++ code

// [[Rcpp::export]]
arma::vec testnumericVec(arma::vec x) {
 x.print("Convert R vector to arma::vec:");
 return x * 2;
}
// [[Rcpp::export]]
arma::mat testnumericMat(arma::mat x) {
 x.print("Convert R matrix to arma::vec:");
 return x * 2;
}
# R code

> sourceCpp("main.cpp")
> y = testnumericVec(1:3)
Convert R vector to arma::vec:
   1.0000
   2.0000
   3.0000
> y
     [,1]
[1,]    2
[2,]    4
[3,]    6
> z = testnumericMat(matrix(1:4, 2))
Convert R matrix to arma::vec:
   1.0000   3.0000
   2.0000   4.0000
> z
     [,1] [,2]
[1,]    2    6
[2,]    4    8

Very nice work!

0 comments: