用列表将R矩阵转换为arma::mat

用列表将R矩阵转换为arma::mat,r,rcpp,armadillo,rcpparmadillo,R,Rcpp,Armadillo,Rcpparmadillo,我想在矩阵列表中使用arma::mat 将R矩阵转换为arma::mat可以很好地使用const 但当我使用带有矩阵的列表作为参数时,它需要很长时间 #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] using namespace Rcpp; using namespace arma; // [[Rcpp::export]] int check1(List X) { int i; for (i

我想在矩阵列表中使用arma::mat

将R矩阵转换为arma::mat可以很好地使用const

但当我使用带有矩阵的列表作为参数时,它需要很长时间

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
int check1(List X)
{
   int i;
   for (i = 0; i < 10; i ++)
      arma::mat y = as<arma::mat>(X[i]);
   return 0;
}
// [[Rcpp::export]]
int check2(const List& X)
{
   int i;
   for (i = 0; i < 10; i ++)
      arma::mat y = as<arma::mat>(X[i]);
   return 0;
}
// [[Rcpp::export]]
int check3(List X)
{
   int i;
   for (i = 0; i < 10; i ++)
      NumericMatrix y = X[i];
   return 0;
}

似乎出现了一些拷贝,这会减慢代码的速度

为了防止在创建犰狳矩阵时复制,一种解决方案是:

// [[Rcpp::export]]
int check4(List X)
{
  int i;
  for (i = 0; i < 10; i ++) {
    NumericMatrix x = X[i];
    arma::mat y = arma::mat(x.begin(), x.nrow(), x.ncol(), false);
  }
  return 0;
}

PS:const和&不会对您的Rcpp代码进行任何更改。请参阅的第5.1节。

使用是一条可行之路。对于常量arma::mat和arguments,这会自动发生!您对Rcpp常见问题解答第5.1节的阅读不太正确。由于代理模型的原因,&是多余的,可以通过从假定的const创建一个新的SEXP来绕过const,但是const将阻止您修改原始SEXP。在诸如x的数据上尝试以下函数:void const_modconst Rcpp::IntegerVector&x{x=x+1;}
// [[Rcpp::export]]
int check4(List X)
{
  int i;
  for (i = 0; i < 10; i ++) {
    NumericMatrix x = X[i];
    arma::mat y = arma::mat(x.begin(), x.nrow(), x.ncol(), false);
  }
  return 0;
}
Unit: microseconds
    expr     min       lq      mean   median       uq      max neval
    arma 599.669 606.5465 634.41683 610.4185 632.4370 1519.262   100
   carma 600.506 606.0975 624.18013 609.8885 629.5135 1327.891   100
      nm   2.100   2.5030  10.88695   3.5180   4.2670  743.220   100
 nm_arma   2.949   3.3160  11.48330   4.7625   5.3195  685.302   100