[Rcpp-devel] Rcpp / RcppArmadillo storage

Dirk Eddelbuettel edd at debian.org
Wed Feb 19 00:39:36 CET 2014


Hi Gregor,

On 18 February 2014 at 15:28, Gregor Kastner wrote:
| I suppose this is a common task, nevertheless I could not find any
| posts/documentation on it. Please excuse me if I missed something, I'd
| appreciate any pointers.
| 
| What I'd like to do is the following:
| 
| I have a function "myfun" (that I don't want to modify because it's used
| elsewhere) which is called often, thus copies of variables should be
| minimized. The results of the computations in myfun should be stored in an
| RcppArmadillo cube, where results from call 1 are stored in slice 1, results
| from call 2 are stored in slice 2 etc. The current slice is also needed as
| input to the function, its values should be simply overwritten.
| 
| To be more concrete: I'd like to call
| 
| void myfun(NumericMatrix &data) {
|  // some complex operations
|  data = data + data;
|  // some more complex operations
| }
| 
| as follows:
| 
| arma::cube results(10, 20, 100, fill::randu);
| 
| for (int i = 0; i < 100; i++) {
|  myfun(results.slice(i));
| }
| 
| This fails with:
| 
| error: invalid initialization of reference of type ‘Rcpp::NumericMatrix& {aka
| Rcpp::Matrix<14>&}’ from expression of type ‘arma::Mat<double>’
| 
| If instead I use:
| 
| void myfun(arma::mat &data) {
|  // some complex operations
|  data = data + data;
|  // some more complex operations
| }
| 
| everything works fine (but, like said above, I can't modify myfun).
| 
| Any ideas, suggestions?

I am not sure I really follow.  But let me try:

 1)  'data + data' may work for Armadillo because Armadillo generally has
     much better support for math operations. We know of some shortcomings in
     our code there (see TODO and/or Issue list on Github, help is welcome).

 2)  you may get by with a simple as<> or wrap call

 3)  else, and I just had to that with code this weekend, split the
     assignments into several lines -- the template code is pretty ambitious
     and for compound operations it sometimes rubs the compile the wrong way.
     Ie try

         NumericMatrix tmp = results.slice(i);  // even wrap as neeed
         myfun(tmp);

etc pp.

Cheers, Dirk

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


More information about the Rcpp-devel mailing list