Last active
September 29, 2021 00:33
-
-
Save OlivierBinette/3ad64c5edadfc1326cbf408206297c1a to your computer and use it in GitHub Desktop.
[Multivariate Normal Sampling]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(assert) | |
rmultinorm.fast <- function(k, mu, sigma) { | |
p = length(mu) | |
t(chol(sigma)) %*% matrix(rnorm(p*k, 0, 1), nrow=p) + mu | |
} | |
#' Sample from a multivariate normal distribution. Attaches both `rmultinorm` | |
#' and `rmultinorm.fast` to the current environment. | |
#' | |
#' @param k Number of samples | |
#' @param mu Mean vector of the distribution | |
#' @param sigma Covariance matrix | |
#' @return A matrix (of dimension length(mu) x k) with columns corresponding to | |
#' independent draws from the multivariate normal distribution. | |
#' | |
#' @examples | |
#' mu = c(-10, 10) | |
#' sigma = matrix(c(1,0,0,1), nrow=2) | |
#' r = rmultinorm(1000, mu, sigma) | |
#' hist(c(1,1) %*% r) | |
rmultinorm <- function(k, mu, sigma) { | |
assert(is.numeric(k), | |
length(k) == 1, | |
k > 0, | |
is.numeric(mu), | |
is.matrix(sigma), | |
all(length(mu) == dim(sigma))) | |
return(rmultinorm.fast(k, mu, sigma)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment