RcppArmadillo:arma :: cube' s的向量

时间:2018-04-19 16:05:19

标签: c++ r rcpp armadillo

我正在使用RcppArmadillo在R / Rcpp中开发应用程序,我需要使用arma :: cube对象的向量。以下示例工作正常。

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

using namespace std;
using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
bool posterior(int n, int L, NumericVector N, int TIME) {
    vector<cube> A(TIME);
    for (int t = 0; t < TIME; t++) A[t] = cube(n, L, max(N), fill::zeros);

    Rprintf("*** %.2f ***\n", A[3].at(5, 1, 2));

    return true;
}

这是一些测试它的R代码。

library(Rcpp)

sourceCpp("VectorOfCubes.cpp")

posterior(200, 3, c(10, 5, 2), 10^4)

我的问题是:我可以消除上面C ++函数中的for并直接初始化向量A吗?

1 个答案:

答案 0 :(得分:4)

为什么不使用默认的vector构造函数?

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
bool posterior_default(int n, int L, Rcpp::NumericVector N, int TIME) {
  std::vector<arma::cube> A(TIME, arma::cube(n, L, max(N), arma::fill::zeros));

  return true;
}

您可以使用std::fill算法,c.f。

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
bool posterior(int n, int L, Rcpp::NumericVector N, int TIME) {
  std::vector<arma::cube> A(TIME);

  std::fill(A.begin(), A.end(), arma::cube(n, L, max(N), arma::fill::zeros));

  return true;
}

但是,更简单的变体是使用arma::field来存储值而不是std::vector,然后使用.fill()成员函数。

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::field<arma::cube> posterior_field(int n, int L, Rcpp::NumericVector N, int TIME) {
  arma::field<arma::cube> A(TIME);

  A.fill(arma::cube(n, L, max(N), arma::fill::zeros));

  return A;
}

输出:

posterior_field(3, 4, c(1,2,3), 10)
#      [,1]      
# [1,] Numeric,36
# [2,] Numeric,36
# [3,] Numeric,36
# [4,] Numeric,36
# [5,] Numeric,36
# [6,] Numeric,36
# [7,] Numeric,36
# [8,] Numeric,36
# [9,] Numeric,36
# [10,] Numeric,36
相关问题