在 Rcpp 中生成多元高斯分布

Generating multivariate Gaussian distribution in Rcpp

我在这里 link 使用了一些 Rcpp 代码来从多元高斯分布中生成样本:https://gallery.rcpp.org/articles/simulate-multivariate-normal/

Rcpp 代码:

#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代码:

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

这在最近之前工作正常,但我收到以下错误:

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

还有其他人遇到这个问题吗?

非常感谢任何帮助!

适用于我今天上传到 CRAN 的版本。您声称哪个版本有错误?

R> library(RcppArmadillo)
R> packageVersion("RcppArmadillo")
[1] ‘0.9.700.2.0’
R> Rcpp::sourceCpp("~/git/Whosebug/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>

我按原样使用了您的 C++ 代码,只是将 Sigma 调整为小写 sigma。