%Aug. 2006 oppg 3b)

mu0 = 2.4; sig = 0.21; N = 24; alpha = 0.05; conf=1-alpha;
cutoff = norminv(alpha, mu0, sig/sqrt(N));

%Finn forkastningsområdet

x = [linspace(2.0,cutoff), linspace(cutoff,2.6)];
y = normpdf(x,mu0,sig/sqrt(N));
h1 = plot(x,y);
xhi = [x(x<=cutoff),cutoff]; yhi = [y(x<=cutoff),0];
patch(xhi,yhi,'b');
title(['Fordelinga til utvals gjennomsnittet, N=',num2str(N)]);
xlabel('gjennomsnitt'); ylabel('sannsynstettheit');
text(2.35,3,sprintf('Forkast dersom gjennomsnitt <%.4g\n alpha = 0.05',cutoff),'Color','b')

%Finn styrken for mu_1=2.30

mu1 = 2.3;
y2 = normpdf(x,mu1,sig/sqrt(N));
h2 = line(x,y2,'Color','r');
yhi = [y2(x<=cutoff),0];
patch(xhi,yhi,'r','FaceAlpha',0.25);
P = normcdf(cutoff,mu1,sig/sqrt(N));
text(2.02,3,sprintf('Forkast dersom gj.snitt<%.4g\nStyrke = %.2g',cutoff,P),'Color',[1 0 0]);
legend([h1 h2],'Null hypotese','Alternativ hypotese');


%Visialisert med kummulativ fordelingsfunksjon

ynull = normcdf(x,mu0,sig/sqrt(N));
yalt = normcdf(x,mu1,sig/sqrt(N));
h12 = plot(x,ynull,'b-',x,yalt,'r-');
zval = norminv(alpha);
cutoff = mu0 + zval * sig / sqrt(N);
line([2.0,cutoff,cutoff],[alpha, alpha, 0],'LineStyle',':');
%msg = sprintf(' Cutoff = 100 + %.2g \\times 20 / \\surd{n}',zval);
%text(cutoff,.15,msg,'Color','b');
text(min(x),alpha,sprintf('   %g%% test',100*alpha),'Color','b',...
                         'verticalalignment','top')
palt = normcdf(cutoff,mu1,sig/sqrt(N));
line([2.0,cutoff],[palt,palt],'Color','r','LineStyle',':');
line([cutoff,cutoff],[0,palt],'Color','r','LineStyle',':')
text(2.0,palt+.02,sprintf(' Styrke er %.2g',palt),'Color',[1 0 0]);
legend(h12,'Null hypothesis','Alternative hypothesis');

DesiredPower = 0.90;
Nvec = 1:50;
cutoff = mu0 - norminv(1-alpha)*sig./sqrt(Nvec);
power = normcdf(cutoff, mu1, sig./sqrt(Nvec));
plot(Nvec,power,'bo-',[0 50],[DesiredPower DesiredPower],'k:');
xlabel('N = antall observasjonar'); ylabel('Power')
title('Styrkefunksjon for alternativet: \mu = 2.3')