% LMEx060401_4th.m
% Larsen & Marx (2006) Introduction to Mathematical Statistics, 4th ed
% Written by Eugene.Gallagher@umb.edu, 3/10/11 revised 3/10/11
muo=100;sigma=14;Power=.6;muh1=103;alpha=0.05
N = sampsizepwr('z',[muo sigma],muh1,Power,[],'alpha',alpha,'tail','right');
fprintf('%2.0f samples must be taken to achieve power=%2.0f%%\n',N,Power*100);
% Optional, just checking why L&M said 78 was adequate
% What is th exact value of n needed; use an anonymous function to solve n
initialguess=75
x=fsolve(@(n) 100+norminv(0.95)*14/sqrt(n)-(103-0.25*14/sqrt(n)),...
    initialguess,optimset('Display','off'));
fprintf('The exact sample size required is %6.4f\n',x);
% Larsen & Marx report 78 so check the power with 78. 
n=78; 
Power = sampsizepwr('z',[muo sigma],muh1,[],n,'alpha',alpha,'tail','right');
fprintf('One-tailed test: the power with n=%2.0f is %5.2f%%.\n',n,Power*100)
% Another way to calculate power, should be identical
CriticalValue=norminv(1-alpha,muo,sigma/sqrt(n));
Power2=1-normcdf(CriticalValue,muh1,sigma/sqrt(n));
fprintf('One-tailed test: the power with n=%2.0f is %5.2f%%.\n',n,Power2*100)
% note that if the test were two-tailed, here is how these functions would
% be called:
Power = sampsizepwr('z',[muo sigma],muh1,[],n,'alpha',alpha,'tail','both');
fprintf('Two-tailed test: the power with n=%2.0f is %5.2f%%.\n',n,Power*100);
CriticalValue2=norminv(1-alpha/2,muo,sigma/sqrt(n));
Power2=1-normcdf(CriticalValue2,muh1,sigma/sqrt(n));
fprintf('Two-tailed test: the power with n=%2.0f is %5.2f%%.\n',n,Power2*100)