[Rcpp-devel] Filling NumericMatrix with NumericVectors with apply by row/column?

Christian Gunning xian at unm.edu
Tue Sep 21 10:57:27 CEST 2010


On Tue, Sep 7, 2010 at 11:40 PM, Romain Francois
<romain at r-enthusiasts.com> wrote:
>>
>> In the first case, could I conceivably turn an input 3D SEXP array
>> into, e.g., NumericVector( Dimension(2,3,4) ), create an arma::cube
>> out of it, process it and return?
>
> I think so. I have not tried though ... have you ?

Here we go - it works under certain circumstances:

fx_flat <- cxxfunction( signature(x = "integer", y = "array" ) ,
  '
    NumericVector ret(Dimension(2,2,2));
    ret = NumericVector(y);
    ret = ret * as<int>(x);  // this "squishes" ret back to 1D
    return ret;
  ', plugin = "RcppArmadillo" )

> fx_flat( 2L, array(1:8, dim=c(2,2,2)) )
[1]  2  4  6  8 10 12 14 16

fx_cube <- cxxfunction( signature(x = "integer", y = "array" ) ,
  '
      // note - NumericVector ret(y) is flat
    NumericVector ret(Dimension(2,2,2));
      // use copy constructor to keep dimension
    ret = NumericVector(y);
      // copy_aux_mem = false is the only way to return retcube?
    arma::cube retcube(ret.begin(), 2, 2, 2, false);
    retcube = retcube * as<int>(x);
    return ret;
  ', plugin = "RcppArmadillo" )

> fx_cube( 2L, array(1:8, dim=c(2,2,2)) )
, , 1
     [,1] [,2]
[1,]    2    6
[2,]    4    8
, , 2
     [,1] [,2]
[1,]   10   14
[2,]   12   16

A few points stand out to me -

* If i'm not doing pointer-magic and/or only using Rcpp/Armadillo
operators, is copy_aux_mem = false a reasonable way to return retcube
after processing?  I don't see any other way to get an SEXP out of an
arma::cube, but i'm skeptical of "can be dangerous unless you know",
since i don't.

* It seems to me that row/column/slice indexer semantics, rather than
linearArray[ thisrow + thiscol*(ncol-1) ] semantics (which i always
seem to mess up) is one reason these mailing list questions about
arrays keep popping up.

* What about "ret = ret * as<int>(x);" causes ret to lose it's dimension?

best,
Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!


More information about the Rcpp-devel mailing list