Define a matrix in R and pass it to C++

╄→гoц情女王★ 提交于 2019-12-07 06:04:47

问题


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.


回答1:


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    



回答2:


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.



来源:https://stackoverflow.com/questions/13324664/define-a-matrix-in-r-and-pass-it-to-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!