我正在为吉布斯采样制作 Rcpp 代码。在代码中,我首先想要创建一个 3 维数组,其中行数 = 迭代次数 (500),列数 = 参数数 (4),切片数 = 链数 (3)。我是这样写的:
#include <RcppArmadillo.h>
#include <math.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace std;
using namespace arma;
//Gibbs sampling code starts here
Rcpp::List mcmc(const int iter,const int chains, const NumericVector data){
arma::cube posteriorC = arma::zeros(iter, 5, chains);
\\ rest of the codes
List out(Rcpp::List::create(Rcpp::Named("posteriorC") =posteriorC));
return out;
}
。虽然引人注目,但它不会显示任何错误。但是当我想运行代码时:
res<- mcmc(iter=500,chains=2,data)
它显示错误:
Error: Cube::operator(): index out of bounds
。我想知道制作3D阵列时是否有任何错误。请注意,我想要估计模型的 5 个参数。
您需要指定模板arma::zeros
正确填写arma::cube
, c.f. arma::zeros<template> http://arma.sourceforge.net/docs.html#zeros_standalone
生成元素设置为零的向量、矩阵或立方体
Usage:
vector_type v = zeros<vector_type>( n_elem )
matrix_type X = zeros<matrix_type>( n_rows, n_cols )
matrix_type Y = zeros<matrix_type>( size(X) )
cube_type Q = zeros<cube_type>( n_rows, n_cols, n_slices )
cube_type R = zeros<cube_type>( size(Q) )
因此,在你的情况下它将是:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
Rcpp::List mcmc(const int iter, const int chains,
const Rcpp::NumericVector data){
arma::cube posteriorC = arma::zeros<arma::cube>(iter, 5, chains);
// --------------------------------- ^^^^^^^^
// Not Shown
Rcpp::List out = Rcpp::List::create(Rcpp::Named("posteriorC") =posteriorC);
return out;
}
最后两个注意事项:
- 您明确声明现在的代码将创建4要存储的列4变量。但是,您明确提到您需要估计5参数。您可能需要增加此值以防止在保存到
arma::cube
切片。
- 方式
Rcpp::List out
正在创建并不完全正确。一般来说,创建列表的最佳方法是:Rcpp::List out = Rcpp::List::create(Rcpp::Named("Blah"), Blah);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)