Skip to content

Instantly share code, notes, and snippets.

@drbenvincent
Created December 10, 2015 20:52
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 drbenvincent/b0549ff1ae428a3428b1 to your computer and use it in GitHub Desktop.
Save drbenvincent/b0549ff1ae428a3428b1 to your computer and use it in GitHub Desktop.
quick example of importance sampling
%% true probability distribution
true_func = @(x) betapdf(x,1+1,1+10);
%% Do importance sampling
N = 10^6;
% uniform proposal distribution
x_samples = rand(N,1);
proposal = 1/N;
% evaluate for each sample
target = true_func(x_samples);
% calculate importance weight
w = target ./ proposal;
w = w ./ sum(w);
% resample, with replacement, according to importance weight
samples = randsample(x_samples,N,true,w);
%% plot
subplot(1,2,1)
x = linspace(0,1,1000);
plot(x, true_func(x) )
axis square
subplot(1,2,2)
hist(samples,1000)
title('importance sampling')
axis square
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment