使用列表将R矩阵转换为arma :: mat [英] Converting R matrix to arma::mat with List

查看:94
本文介绍了使用列表将R矩阵转换为arma :: mat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用arma :: mat作为我的矩阵列表.

I want to use arma::mat for my list of matrices.

将R矩阵转换为arma :: mat与const的效果很好.

Converting R matrix to arma::mat is working well with const.

但是当我使用带有矩阵的List作为参数时,它会花费很长时间.

But when i use List with matrices as an arguments, It takes very long time.

#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

推荐答案

似乎正在发生一些复制,这会降低代码的速度.

It seems that there are some copies happening, which slows down your code.

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

To prevent copies when creating Armadillo matrices, one solution is:

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

PS: const and & won't change anything to your Rcpp code. See section 5.1 of https://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-FAQ.pdf.

这篇关于使用列表将R矩阵转换为arma :: mat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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