11/21/2010

How to draw a multivariable Gaussian random variable?

% Create Gaussian d-dimensional random variable
% Using Cholesky factorization
% Input: 
%   mu: mean vector, d-by-1
%   cov: covariance matrix, positive definite, d-by-d
%   n:  number of samples, =100 default
% Output:
%   X: d-by-n, each column is a sample
%-------------------
% trungd@okstate.edu
% Example
% x = gauss_d;
% y = gauss_d([0;5],[1 .9;.9 1],200);
% figure, hold on
% scatter(x(1,:),x(2,:))
% scatter(y(1,:),y(2,:))

function X = gauss_d(mu,covm,n)
if nargin<3, n=100;end
if nargin<2, covm=[1 0;0 1]; end
if nargin<1, mu=[0 0]; end
% -------------------
% Better to check size of mu, covm here
% I am lazy to do that :)
% -------------------
mu = mu(:)'; % make sure be row
d = length(mu);
% Get Cholesky factorization of covariance.
R = chol(covm);
% Generate the standard normal random variables.
Z = randn(n,d);
X = Z*R + repmat(mu,n,1);
X = X';

Two 2-D Gaussian random variables' samples

2 comments:

Anonymous said...

Hey, I am checking this blog using the phone and this appears to be kind of odd. Thought you'd wish to know. This is a great write-up nevertheless, did not mess that up.

- David

Anonymous said...

I seldom leave comments on blog, but I have been to this post which was recommend by my friend, lots of valuable details, thanks again.