% LMcs070502_4th.m
% Page 505-506 in
% Larsen & Marx (2006) Introduction to Mathematical Statistics, 4th edition
% Written by Eugene.Gallagher@umb.edu
X=[6.38;6.63;6.88;6.75;6.13;6.50;6.63;6.38;6.50];n=length(X);df=n-1;
sd=.1;alpha=0.05;
fprintf(...
'The variance for 30-y fixed mortgages = %5.3f%% and 1-year adjustables = %5.3f%%\n',...
sd^2,var(X))
[H,P,CI,STATS] = vartest(X,sd^2,alpha,'both')
if H==1
    fprintf('Reject the null hypothesis\n')
else
    fprintf('Fail to reject the null hypothesis\n')
end
% Or using theorem 7.5.2
chi2=df*var(X)/sd^2
pvalue1tail=(1-chi2cdf(chi2,df));
pvalue2tail=pvalue1tail*2;
fprintf('The two-tailed p-value for chi2 = %6.2f & %1.0f df is %5.2e\n',chi2,df,pvalue2tail)
% Plot the chi square distribution using Figure 7.5.1 as a model
chi95=chi2inv(0.95,df);
zmax=24;
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 0.13])
set(gca,'Ytick',[0:.04:0.12],'FontSize',18)
set(gca,'Xtick',[0:4:12 chi95 20],'FontSize',18)
ax=axis;
ax1=gca; % save the handle of the graph
title('Figure 7.5.3','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='Area=0.05';
text(chi95,.02,t,'Color','b','FontSize',20);
figure(gcf)
hold off
