% Analyse de la variance a 2 facteurs
% Examen 2002

% Entree des effectifs

clear
p=3;q=3;r=4;n=p*q*r;
% Entree des donnees

Y11=[620 612 615 627];
Y12=[670 631 628 614];
Y13=[704 679 687 707];
Y21=[586 618 604 614];
Y22=[662 678 597 619];
Y23=[711 678 682 649];
Y31=[591 622 579 574];
Y32=[623 647 580 607];
Y33=[671 623 597 615];


Y=[Y11 Y12 Y13 Y21 Y22 Y23 Y31 Y32 Y33]';
X=zeros(n,p*q);
min=0;max=n;cp=0;
for i=1:p,
    for j=1:q,
        X(:,cp+j)=[zeros(min,1);ones(r,1);zeros(max-min-r,1)];
        min=min+r;
    end
	cp=cp+j;
end
% Estimation
%%%%%%%%%%%%%%%%%%
XX=X'*X;
m=inv(XX)*X'*Y;
Ychap=X*m;
%%%%%%%%%%%%%%%%%%
mu=mean(m);
for i=1:p,
    al(i)=mean(m(q*(i-1)+1:q*i));
end
al=al';
a=al-mu*ones(p,1);
bc=zeros(q,1);
for j=1:q,
    for i=1:p,
    bc(j)=bc(j)+m(j+q*(i-1));
    end 
    bc(j)=bc(j)/p;
end
b=bc-mu*ones(q,1);
at=[];bt=[];
for i=1:p,
    at=[at;a(i)*ones(q,1)];
    bt=[bt;b];
end 
    mut=mu*ones(p*q,1);
c=m-at-bt-mut; 
sigma2=((norm(Y-Ychap))^2)/(n-(p*q));
SR=(norm(Y-Ychap))^2;
ST=(norm(Y-mu*ones(n,1)))^2;
Sa=q*r*sum(a.^2);
Sb=p*r*sum(b.^2);
Sc=r*sum(c.^2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Test de Fisher absence d'interaction
Ytild=X*(mut+at+bt);
d=(norm(Ychap-Ytild))^2;
F=d/((p-1)*(q-1)*sigma2);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Test de Fisher absence d'effet facteur 1
Ytd1=X*(mut+bt);
d1=(norm(Ychap-Ytd1))^2;
F1=d1/((p-1)*(q)*sigma2);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Test de Fisher absence d'effet facteur 2
Ytd2=X*(mut+at);
d2=(norm(Ychap-Ytd2))^2;
F2=d2/((p)*(q-1)*sigma2);




