r - 使用 List 将 R 矩阵转换为 arma::mat

标签 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 = 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;
}
matlist = lapply(1:10, function(x) matrix(rnorm(10000), 2000, 50))
microbenchmark::microbenchmark(
   arma = check1(matlist),
   carma = check2(matlist),
   nm = check3(matlist)
)
Unit: microseconds
  expr     min       lq      mean  median      uq      max neval
  arma 558.081 597.6485 622.13757 614.702 625.928 1303.494   100
 carma 551.950 600.4425 658.33583 612.761 626.683 1749.153   100
    nm   2.288   4.3590   5.57801   5.123   5.901   39.743   100

最佳答案

似乎发生了一些副本,这会减慢您的代码速度。

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

// [[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

PS:const& 不会对您的 Rcpp 代码进行任何更改。请参阅 https://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-FAQ.pdf 的第 5.1 节.

关于r - 使用 List 将 R 矩阵转换为 arma::mat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57516726/

相关文章:

r - 设置数据框列表列表的格式

r - 在查找表中使用多个引用值

r - 如何检测和标记另一列中一列的变化

c++ - 为什么我的 Rcpp 代码会给出意外的所有整数值输出?

c++ - Armadillo cpp : access slice of a 3D field

r - 将逗号分隔的单元格分隔到新行

R:大向量的高效迭代子集和过滤

r - 如何调整 NumericVector 的大小?

c++ - Armadillo 的solve(A, b)从Matlab、Eigen返回不同的答案

c++ - 使用文件路径访问 Armadillo 库 C++ Linux OS