Skip to content

Instantly share code, notes, and snippets.

@karlnapf
Last active December 16, 2015 03:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlnapf/5371082 to your computer and use it in GitHub Desktop.
Save karlnapf/5371082 to your computer and use it in GitHub Desktop.
how to sample a Gaussian given covariance or precision with symamd
% samples from N(mu, C) in case type=='cov', and from N(mu, C^(-1)) in case
% type=='prec'. z is optional and must be drawn from N(0,I), inds is a
% permutations vector that is applied to C before sampling (doesnt effect
% the output, just efficiency, smyamd is used as default)
function sample=gaussian_sampler_symamd(mu, C, type, z, inds)
if nargin<3
type='prec';
end
if nargin <4
z=randn(size(C,1),1);
end
if nargin < 5
inds=symamd(C);
end
% inverse permutation
inds_inv(inds)=1:length(inds);
% permute input gaussian
z=z(inds);
% cholesky C_L'*C_L==C(inds,inds)
C_L=chol(C(inds,inds));
if strcmp(type, 'cov')
% draw a sample from N(0, C(inds,inds))
x=C_L'*z;
else
% draw a sample from N(0, C^(-1)(inds,inds))
x=C_L\z;
end
% undo permutation, this is a sample from N(0, C^(-1)) or N(0, C), then add mean
sample=x(inds_inv)+mu;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment