2017-10-11 71 views
1

我正在製作用於吉布斯採樣的Rcpp代碼。在代碼裏面,我首先要創建一個三維數組,其中行數=迭代次數(500),列號=參數數量(4),切片數量=鏈數(3)。我這樣寫:在Rcpp中製作帶有arma :: cube的三維數組顯示多維數據集錯誤

#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個參數。

回答

0

您需要指定arma::zeros的模板以正確填寫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))

因此,在你的情況將是:

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

最後兩個注意事項:

  1. 您明確指出,因爲它現在站立的代碼將創建列存儲變量。但是,您明確提到您需要估計參數。您可能需要增加此功能以防止在保存到arma::cube切片時出現越界。
  2. 正在創建Rcpp::List out的方式不太正確。一般來說,創建清單的最佳方式是:Rcpp::List out = Rcpp::List::create(Rcpp::Named("Blah"), Blah);
+0

@ coatless,非常感謝。但它不適合我。 :(編寫或編譯時不顯示任何錯誤,我可以同時使用arma :: cube和Rcpp :: NumericVector嗎?或者我總是隻需要使用arma? – gultu

+0

@gultu我有0個線索你的MCMC例程中發生了什麼,因爲你忽略了它。我不能診斷_why_它不適合你,因爲我所擁有的信息很稀疏,並且直接與'arma :: cube'的實例化有關 – coatless

+0

@ coatless ,主代碼很長並且很複雜,我應該在這裏發佈嗎? – gultu