making 3d array with arma::cube in Rcpp shows cube error

扶醉桌前 提交于 2019-12-11 00:57:00

问题


I am making a Rcpp code for Gibbs sampling. Inside the code, I first want to make a 3 dimensional array with row number= number of iteration (500), column number=number of parameter(4) and slice number= number of chain(3). I wrote it in this way:

#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;
}

. While compelling it does not show any error. But when I want to run the code with:

res<- mcmc(iter=500,chains=2,data)

it shows the error:

Error: Cube::operator(): index out of bounds

. I want to know if there any mistake while making the 3D array. Please note that I want to get estimates of 5 parameters of my model.


回答1:


You need to specify the template for arma::zeros to correctly fill an arma::cube, c.f. arma::zeros<template>

Generate a vector, matrix or cube with the elements set to zero

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) )

Thus, in your case it would be:

#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;
}

Two final notes:

  1. You explicitly state that the code as it stands now will create 4 columns to store 4 variables. However, you explicitly mention that you needed to estimate 5 parameters. You may need to increase this to prevent an out of bounds when saving into the arma::cube slices.
  2. The way the Rcpp::List out is being created isn't quite correct. In general, the best way to create the list is to do: Rcpp::List out = Rcpp::List::create(Rcpp::Named("Blah"), Blah);


来源:https://stackoverflow.com/questions/46688437/making-3d-array-with-armacube-in-rcpp-shows-cube-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!