function CLT()
% Demo of central limit theorem
% Jerry Zhu

% generate n beta(.5,.5) random variables.
% compute Z_n.
% repeat this procedure a large number of times so we can plot the histogram of Z_n.

for n=1:9,
  runCLT(n);
end

function runCLT(n)
ntrials=100000;
% each column is a trial.
% each row is a random uniform(-1,1) number
X = betarnd(0.5, 0.5, n, ntrials);
Z = sqrt(8*n)*(mean(X,1)-0.5);

% CDF
figure(1)
subplot(3,3,n); 
hold on
plot(-5:.1:5, normcdf(-5:.1:5,0,1), 'r-');
for t=-5:.1:5;
  plot(t, length(find(Z<=t))/ntrials,'.')
end
s=sprintf('n=%d',n);
title(s);
%legend('CDF N(0,1)', 'CDF Z_n',2);

% PDF
figure(2)
subplot(3,3,n); 
hist(Z,100)
s=sprintf('n=%d',n);
title(s);
axis([-5 5 0 4000])
