
% Longin Jan Latecki, latecki@temple.edu, Sep. 2009
% plots histogram of samples drawn from a Gaussian with mean zero and std one
% and plots the Gaussian with mean zero and std one
% the values of histogram are normalized so that the sum of the area of the
% histgoram bars (rectangles) is equal to one
% This way both plots are directly comparable, since the area under the
% Gaussian curve is also one.

x = -5:0.1:5;
g=normpdf(x,0,1);
N=1000; %number of samples
samples=randn(N,1);
%samples = normrnd(0,1,1000,1);
[hs, hx] = hist(samples,x); %hs is a vector with the number of elements in each histogram bin; hx are the coordinates of bin centers
hs=(hs/N)*(101/10); %101==length(x)
figure; bar(x,hs,'r'); %plots normalized histogram
hold on
plot(x,g,'LineWidth',3); %plots the Gaussian
title('Gaussian G(0,1) and the histogram of samples from G(0,1)')


%Kernel density estimate
sigma=0.1;
for i=1:length(x)
    f(i)=(1/N)*sum(normpdf(x(i)-samples,0,sigma)); %we have a gaussian centered at each sample point
end

figure; plot(x,f,'r','LineWidth',3); %plots the kernel density estimate
hold on
plot(x,g,'LineWidth',3); %plots the Gaussian
title('Gaussian G(0,1) and the kernel density estimate from samples from G(0,1)')
