简体   繁体   中英

Generating multivariate Gaussian distribution in Rcpp

I used this link here for some Rcpp code to generate samples from a multivariate Gaussian distribution: https://gallery.rcpp.org/articles/simulate-multivariate-normal/

Rcpp code:

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

using namespace Rcpp;

// [[Rcpp::export]]
arma::mat mvrnormArma(int n, arma::vec mu, arma::mat sigma) {
   int ncols = sigma.n_cols;
   arma::mat Y = arma::randn(n, ncols);
   return arma::repmat(mu, 1, n).t() + Y * arma::chol(sigma);
}

R code:

mvrnormArma(n = 10000, mu = c(0, 0), Sigma = matrix(c(1,0,0,1), 2, 2))

This worked fine until recently and I get the following error:

error: Mat::init(): requested size is not compatible with column vector layout

Does anyone else have this problem?

Any help is much appreciated!

Works for me with the version uploaded to CRAN today. Which version do you claim an error with?

R> library(RcppArmadillo)
R> packageVersion("RcppArmadillo")
[1] ‘0.9.700.2.0’
R> Rcpp::sourceCpp("~/git/stackoverflow/57760655/question.cpp")

R> #mvrnormArma(n = 10000, mu = c(0, 0), Sigma = matrix(c(1,0,0,1), 2, 2))
R> set.seed(123)  # make it reproducible
R> mvrnormArma(n = 10, mu = c(0, 0), sigma = matrix(c(1,0,0,1), 2, 2))
            [,1]      [,2]
 [1,] -0.6853851  1.811730
 [2,]  0.9302219  0.741069
 [3,] -0.2260918 -0.119390
 [4,]  0.9513753  0.315338
 [5,]  0.0699539  0.670879
 [6,]  0.9767215  0.332053
 [7,]  2.1650415  0.966927
 [8,] -1.8262054  1.294966
 [9,]  0.5804146  1.062635
[10,] -0.0592898  2.270198
R>

I used your C++ code as is, and just adjusted Sigma to lowercase sigma.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM