%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Here is the data from the mites-per-leaf example.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

mites = [0	1	2	3	4	5	6	7   8];     %Number of mites.
leaves= [70	38	17	10	9	3	2	1	0];     %Leaves counted with this many mites.

M = sum(mites.*leaves) / sum(leaves);           %Compute M = avg # of mites per leaf.

Poisson = poisspdf(mites, M)*sum(leaves);       %Construct the Poisson distribution with this M.

figure(1)
bar([Poisson; leaves]', 'group')                %Plot the observed and Poisson distribution.
xlabel('Mites per leaf')
ylabel('# leaves')
title('BLUE=Poisson, RED=Observed Mite Data')

sumterms = (leaves - Poisson).^2.0 ./ Poisson;  %Compute each term in the chi2 sum.

chi2 = sum(sumterms)                            %Here is the chi2-statistic.

figure(2)
plot((0:0.1:30), chi2pdf(0:0.1:30,8))           %Plot the chi2-distribution.
xlabel('\chi^2')
ylabel('\chi^2 Distribution')