Mar 18, 2009

MATLAB code for Sampling Gaussian distribution

function M = sample_gaussian(mu, Sigma, N)
mu = mu(:);
n=length(mu);
[U,D,V] = svd(Sigma);
M = randn(n,N);
M = (U*sqrt(D))*M + mu*ones(1,N);
M = M';

3 comments:

Andrea Prati said...

Dear Yi Wang,
we were experiencing problems with Matlab slicesample function when sampling from a 3-variate Gaussian distribution with mean=[0 0 0] and covariance matrix something like this cov=diag(1e-7, 1e-7, 10). Slicesample seems to fail when samples the third dimension scattering the samples with a very tight variance (not 10, but more like 0.6).

Due to this limitation of slicesample we searched in the web and found your code. And it works great!!! Thanks!

Do you have any paper or notes explaining the method you used?

Thanks
Andrea

GioGiovane said...

Yes,
great piece of code.

Could you tell us what is the theory behind it?

best,
Joe

Yi Wang said...

Hi, Andrea and Joe,

I am sorry for the late response. I did not get Gmail notification about your comments .... do not know why.

I got the idea from this paper: Sampling from the Multivariate Gaussian Distribution using Reconfigurable Hardware, which refers to an even older paper: A comparison of multivariate normal generators.