Skip to content

Instantly share code, notes, and snippets.

@drbenvincent
Last active December 28, 2015 16:03
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save drbenvincent/34c6289a1d3a20c53a0c to your computer and use it in GitHub Desktop.
true_mean = 0;
true_sigma = 1;
% likelihood_func = @(x, mean, sigma) normpdf(x, mean, sigma);
% the above function to calcalate in matrix form, for speed
likelihood_func = @(params)...
prod(normpdf(repmat(x,[1 numel(params(1))]),...
repmat(params(1), [1 numel(x)])',...
repmat(params(2),[1 numel(x)])' ), 1);
%% generate data
global x
N=20;
x = normrnd(true_mean, true_sigma, [N 1]);
%% DO SLICE SAMPLING
initial_samples = [0,1];
nSamples = 10^4;
trace = slicesample(initial_samples, nSamples,...
'burnin', 100,...
'pdf',likelihood_func);
mean_samples = trace(:,1);
sigma_samples = trace(:,2);
subplot(1,2,1)
plot(mean_samples,sigma_samples,'.')
xlabel('mean')
ylabel('sigma')
hold on
plot(true_mean, true_sigma, 'r.','MarkerSize',5^2)
axis square
subplot(2,2,2)
plot(mean_samples)
ylabel('mean')
subplot(2,2,4)
plot(sigma_samples)
ylabel('sigma')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment