% LMcs100301_4th.m
% Larsen & Marx (2006) Introduction to Mathematical Statistics, 4th edition
% Written by Eugene.Gallagher@umb.edu
% Predation on Ceriodaphnia cornuta by Melaniris chagresi
observed=[40 4]
expected=44*[3/4 1/4]
d=sum((observed-expected).^2./expected);
% d=(40-44*3/4)^2/(44*3/4)+(4-44*1/4)^2/(44*1/4);
fprintf('Chi-square statistic = % 6.4f\n',d);
P = 1-chi2cdf(d,1);
fprintf('Chi-squared 2-tailed p-value=%6.4f\n',P);
% the data would be better analyzed by an exact one-sample binomial test
data=40:44;
% 1 tailed exact binomial test
P=sum(binopdf(data,44,3/4));
fprintf('Exact binomial 2-tailed p value=%6.4f from the binomial pdf\n',P*2);
% or solve using the cumulative binomial pdf
P=1-binocdf(39,44,3/4);
fprintf('Exact binomial 1-tailed p value=%6.4f from the binomial cdf\n',P*2);
% Plot the figure and the critical value
% Use Figure 7.5.1 as a model
df=1;chi05=chi2inv(0.05,df);
alpha=0.05;chi95=chi2inv(1-alpha,df);
zmax=7.1; ymax=1.01;
z=0:.01:zmax;
fzz=chi2pdf(z,df);
plot(z,fzz,'linestyle','--','color','r','linewidth',3)
ylabel('Probability Density','FontSize',20)
xlabel('z','FontSize',20)
axis([0 zmax 0 ymax])
set(gca,'Ytick',[0:.2:ymax],'FontSize',18)
set(gca,'Xtick',[0:2:chi95 chi95],'FontSize',18)
ax=axis;
ax1=gca; % save the handle of the graph
title('Figure 10.3.2','FontSize',22)
hold on
fz=chi2pdf(chi95,df);
plot([chi95 chi95]',[0 fz]','-k','linewidth',1) 
% Fill in the upper tail with fill
y2=chi95:.001:ax(2);
fy2=chi2pdf(y2,df);
fymax=chi2pdf(ax(2),df);
fill([chi95 y2 ax(2) ax(2)],[0 fy2 fymax 0],[.8 .8 1])
t=sprintf('Area=0.05');
text(chi95+.01,.1,t,'Color','b','FontSize',20);
figure(gcf)
hold off