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

孤者浪人 提交于 2019-12-05 08:45:51

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.

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