I have a matrix defined in R. I need to pass this matrix to a c++ function and do operations in C++. Example: In R, define a matrix,
A <- matrix(c(9,3,1,6),2,2,byrow=T)
PROTECT( A = AS_NUMERIC(A) );
double* p_A = NUMERIC_POINTER(A);
I need to pass this matrix to a C++ function where variable 'data' of type vector<vector<double>>
will be initialized with the matrix A.
I couldn't seem to figure out how to do this. I am thinking in more complicated way then I should be, I bet there is an easy way to do this.
As Paul said, I would recommend using Rcpp
for that kind of things. But it also depends what you want your vector< vector<double> >
to mean. Assuming you want to store columns, you might process your matrix like this:
require(Rcpp)
require(inline)
fx <- cxxfunction( signature( x_ = "matrix" ), '
NumericMatrix x(x_) ;
int nr = x.nrow(), nc = x.ncol() ;
std::vector< std::vector<double> > vec( nc ) ;
for( int i=0; i<nc; i++){
NumericMatrix::Column col = x(_,i) ;
vec[i].assign( col.begin() , col.end() ) ;
}
// now do whatever with it
// for show here is how Rcpp::wrap can wrap vector<vector<> >
// back to R as a list of numeric vectors
return wrap( vec ) ;
', plugin = "Rcpp" )
fx( A )
# [[1]]
# [1] 9 1
#
# [[2]]
# [1] 3 6
You probably want to use Rcpp. This package allows easy integration of R and C++, including passing objects from R to C++. The package is available on CRAN. In addition, a number of packages on CRAN use Rcpp, so they could serve as inspiration. The website of Rcpp is here:
http://dirk.eddelbuettel.com/code/rcpp.html
which includes a few tutorials.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With