在R中定义一个矩阵,并将其传递给C ++ [英] Define a matrix in R and pass it to C++

查看:135
本文介绍了在R中定义一个矩阵,并将其传递给C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在R中定义的矩阵。我需要将这个矩阵传递给一个c ++函数,并在C ++中执行操作。
示例:在R中,定义一个矩阵,

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);

我需要传递这个矩阵到一个C ++函数,其中变量'data'类型 vector< vector< double>> 将用矩阵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.

做这个。

推荐答案

如同Paul一样,我可以用更复杂的方式思考,说,我建议使用 Rcpp 东西。但它也取决于你想要的向量< vector< double> > 表示。假设你想存储列,你可以这样处理你的矩阵:

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    

这篇关于在R中定义一个矩阵,并将其传递给C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆