Skip to content

Instantly share code, notes, and snippets.

@OlivierBinette
Last active September 29, 2021 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OlivierBinette/3ad64c5edadfc1326cbf408206297c1a to your computer and use it in GitHub Desktop.
Save OlivierBinette/3ad64c5edadfc1326cbf408206297c1a to your computer and use it in GitHub Desktop.
[Multivariate Normal Sampling]
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