r - Index element from list in Rcpp -


suppose have list in rcpp, here called x containing matrices. can extract 1 of elements using x[0] or something. however, how extract specific element of matrix? first thought x[0](0,0) not seem work. tried using * signs doesn't work.

here example code prints matrix (shows matrix can extracted):

library("rcpp")  cppfunction( includes = '  numericmatrix randmat(int nrow, int ncol)  {   int n = nrow * ncol;   numericmatrix res(nrow,ncol);   numericvector rands  = runif(n);    (int = 0; < n; i++)    {     res[i] = rands[i];   }   return(res);  }',  code = ' void foo() {   list x;   x[0] = randmat(3,3);   rf_printvalue(wrap( x[0] )); // prints first matrix in list. } ')   foo() 

how change line rf_printvalue(wrap( x[0] )); here print the element in first row , column? in code want use need extract element computations.

quick ones:

  1. compound expression in c++ can bite @ times; template magic gets in way. assign list object whatever element is, eg numericmatrix.

  2. then pick numericmatrix see fit. have row, col, element, ... access.

  3. printing can easier using rcpp::rcout << anelement note cannot print entire matrices or vectors -- int or double types fine.

edit:

here sample implementation.

#include <rcpp.h>  // [[rcpp::export]] double sacha(rcpp::list l) {     double sum = 0;     (int i=0; i<l.size(); i++) {         rcpp::numericmatrix m = l[i];         double topleft = m(0,0);         sum += topleft;         rcpp::rcout << "element " << topleft << std::endl;     }     return sum;     }  /*** r set.seed(42) l <- list(matrix(rnorm(9),3), matrix(1:9,3), matrix(sqrt(1:4),2)) sasha(l) */ 

and result:

r> rcpp::sourcecpp('/tmp/sacha.cpp')  r> set.seed(42)  r> l <- list(matrix(rnorm(9),3), matrix(1:9,3), matrix(sqrt(1:4),2))  r> sacha(l) element 1.37096 element 1 element 1 [1] 3.37096 r> 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -