【问题标题】:function pass by reference in RcppArmadilloRcppArmadillo中的函数通过引用传递
【发布时间】:2017-05-18 20:23:32
【问题描述】:

我有一个用 RcppArmadillo 风格编写的函数,我想用它来更改调用环境中的变量。我知道这样做是不可取的,但这对我来说很有帮助。具体来说,我正在尝试这个:

#include <RcppArmadillo.h>
#include <iostream>

//[[Rcpp::export]]
void myfun(double &x){
  arma::mat X = arma::randu<arma::mat>(5,5);
  arma::mat Y = X.t()*X;
  arma::mat R1 = chol(Y);

  x = arma::det(R1);
  std::cout << "Inside myfun: x = " << x << std::endl;
}


/*** R
x = 1.0  // initialize x 
myfun(x) // update x to a new value calculated internally
x        // return the new x; it should be different from 1
*/ 

我错过了什么?为什么不工作?

【问题讨论】:

    标签: r rcpp armadillo


    【解决方案1】:

    double 不是本机 R 类型(因此总是正在制作副本)并且不可能传递引用。

    改为使用Rcpp::NumericVector,它是SEXP 类型的代理。这有效:

    R> sourceCpp("/tmp/so44047145.cpp")
    
    R> x = 1.0  
    
    R> myfun(x) 
    Inside myfun: x = 0.0361444
    
    R> x        
    [1] 0.0361444
    R> 
    

    下面是完整的代码,还有一两个小修复:

    #include <RcppArmadillo.h>
    
    // [[Rcpp::depends(RcppArmadillo)]]
    
    //[[Rcpp::export]]
    void myfun(Rcpp::NumericVector &x){
      arma::mat X = arma::randu<arma::mat>(5,5);
      arma::mat Y = X.t()*X;
      arma::mat R1 = chol(Y);
    
      x[0] = arma::det(R1);
      Rcpp::Rcout << "Inside myfun: x = " << x << std::endl;
    }
    
    
    /*** R
    x = 1.0  // initialize x 
    myfun(x) // update x to a new value calculated internally
    x        // return the new x; it should be different from 1
    */ 
    

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      • 2020-01-25
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多