[Rcpp-devel] Rccp code with vector and matrix inputs and matrix output
    Gregor Kastner 
    gregor.kastner at wu.ac.at
       
    Fri Mar 28 12:39:13 CET 2014
    
    
  
Hi Petre,
> The following code works well in R:
> attach(dataqtr)
Not for me, because my vanilla copy of R doesn't know about dataqtr. It's
helpful to provide reproducible examples.
 
> However I am not able to reproduce it using the following Rccp code:
> 
> a<- dataqtr[,LTG]
> b<- dataqtr[,meanLTG]
> 
> src <-'
>  Rcpp::NumericVector a(aa);
>  Rcpp::NumericVector b(bb);
>  Rcpp::NumericMatrix Am (A);
>  int n = a.size();
>  int m = b.size();
>  int T=15;
> 
>  int nrows = Am.nrow();
>  int ncol  = Am.ncol();
> 
>      for (int ii = 1; ii < nrows; ii++) {
>         for (int jj = 1; jj<ncol; jj++)  {
>         Am[ii,jj] =  a[jj] * exp(jj/(T-1)*log( b[jj] / a[jj] ));
>         }}
> return Am;
> '
> fun <- cxxfunction(signature(aa="numeric", bb="numeric",A="numeric"), body
> = src, plugin="Rcpp")
> 
> A<-matrix(data=NA,nrow=100,ncol=13)
> fun(a,b,A)
First, it's more probably more convenient to create A within the Rcpp
section, there is no need to allocate memory within R (as you are probably
used to doing when using .C).
Second, when accessing Rcpp::Matrix elements, you probably want to use A(row,
col) instead of A[row, col] (which is usually used to access 2d-arrays).
Third, as Dirk already mentioned, you probably want to start for loop at ii =
0 (or, respectively, jj = 0).
Best,
/g
    
    
More information about the Rcpp-devel
mailing list