%% Importance Sampling Matlab Implementation:By Shoumik Roychoudhury
%Sampling a Gaussian G(0,1) distribution using Uniform distribution
%U(-5,5) to draw samples
clear all
close all
clc
%%
N =1000;%No. of samples
a = -5;
b = 5;
x = a + (b-a)*rand(N,1);%random samples from uniform distribution U(-5,5)
x = x';
x1 = -5:0.1:5;
p = @(x) 1/(sqrt(2*pi)) *exp(-x.^2/2);%Gaussian distribution p(x) = G(0,1)
q = @(x) 1/(b-a);%Unifrom distribution q(x) = U(-5,5)

ahist=zeros(1,length(x1));%ahist is the weighted histogram
for i = 1:N
    w(i) = p(x(i))/(q(x(i))); %Importance Weights
    samples(i) = x(i);
    [a,b]=min(abs(x(i)-x1));
    ahist(b)=ahist(b)+w(i);
end
%[hs, hx] = hist(samples,x1);
hs=(ahist/length(samples))*(length(x1)/10);
figure(1)
bar(x1,hs); %plots normalized weighted histogram
hold on
plot(x1,p(x1),'r','LineWidth',3); %plots the Gaussian distribution p(x)
title('Importance Sampling')


