% Sample from the normal distribution.
% Plot bargraph, compared with theoretical density.

n=1000
sample=randn(1,n); % Standard normal random variable


binstart=-5
binstop=5
binwidth=.2
binedges=[binstart:binwidth:binstop];

% Determine bin heights so that the area of the bin equals the fraction of
% samples that fell in that bin.  The function `histc' is a little flakey.
% It makes the final bin have width 0, so counts only exact hits on the top
% edge.  But the function 'bar' with option 'histc' basically ignores this 
% last bin, so we're OK.

bincount=histc(sample,binedges); 
binprob=bincount/n;
binheight=binprob/binwidth;

bar(binedges,binheight,'histc')

% Plot the theoretical density. 

hold on
x=binstart:.01:binstop;
y=1/sqrt(2*pi)*exp(-(x.^2)/2);
plot(x,y)
hold off