我有一个在 R 中定义的矩阵。我需要将该矩阵传递给 C++ 函数并在 C++ 中执行操作。
示例:在 R 中,定义一个矩阵,
A <- matrix(c(9,3,1,6),2,2,byrow=T)
PROTECT( A = AS_NUMERIC(A) );
double* p_A = NUMERIC_POINTER(A);
我需要将此矩阵传递给 C++ 函数,其中变量“data”类型vector<vector<double>>
将使用矩阵 A 进行初始化。
我似乎不知道该怎么做。我的思考方式比我应该的更复杂,我敢打赌有一种简单的方法可以做到这一点。
正如保罗所说,我建议使用Rcpp http://dirk.eddelbuettel.com/code/rcpp.html对于那种事情。但这也取决于你想要什么vector< vector<double> >
的意思。假设您想存储列,您可以像这样处理矩阵:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)