
% Here is an example Probability Density Function:  
%A normal distribution with mean=0 and sigma =1

x=(-5:.01:5);
PDF=1/sqrt(2*pi)*exp(-x.^2/2);

%we can plot this:
figure
plot(x,PDF)

%the matlab function 'randn' draws numbers from this distribution
%draw 1000 numbers from this distribution:

N=1000;
X=randn(N,1);

%Now histogram the results:

hist(X)

%Now lets plot the distribution together with the PDF
dx=0.5;
BinCenters=(-5:dx:5);
[counts, BCs]=hist(X,BinCenters); %note BCs should be the same as BinCenters

% PDFs are normalized so the integral is 1
% Lets normalize our histogram results so that we can compare to the PDF

%The normalization condition is such that 
%  sum(A*counts*dx)=1
%Where A is the normalization constant. 

A=1/sum(counts*dx)

%use the 'bar' function to plot like a histogram

figure
bar(BinCenters,A*counts*dx)

%now plot the PDF over the histogram:
PDF=1/sqrt(2*pi)*exp(-BinCenters.^2/2);
hold on %keep old plot
plot(BinCenters,PDF*dx,'r','linewidth',2) 

%Note since we have finite sized bins, and a continuous PDF, to get the
%probability of a count in the bin, multiply by 'dx'.  This works if 'dx'
%is small enough, otherwise an intergral of the PDF over the bin width
%would be required. 

%now add some figure labels and legends:

xlabel('x (arbitray unit)','fontsize',14)
ylabel('Counts','fontsize',14)
legend('Normlized counts','PDF')








