function [nest1] = nest1(X)
%Two-level nested analysis of variance design with equal sample sizes.
%(referred to the levels of nested factor). 
%
%   Syntax: function [nest1] = nest1(X) 
%      
%     Inputs:
%          X - data matrix.
%      (column 1:data; column 2:main factor; column 3:nested factor).
%     Output:
%          No. of levels of main factor.
%          No. of levels of nested factor.
%          Complete analysis of variance table.
%
%    Example: From the excercise 15.1 from Zar (1999, p. 311) for a two-level nested 
%             analysis of variance with equal sample sizes Model II.
%
%             Total data matrix must be:
%    X=[1.1 1 1;1.2 1 1;1.3 1 2;1.1 1 2;1.2 1 3;1.0 1 3;1.3 2 1;1.4 2 1;1.3 2 2;
%    1.5 2 2;1.4 2 3;1.2 2 3;1.8 3 1;2.0 3 1;2.1 3 2;2.0 3 2;2.2 3 3;1.9 3 3];
%
%             Calling on Matlab the function: 
%                nest1(X)
%
%       Immediately it display:
%  The number of levels of main factor are: 3
%  The number of levels of nested factor are: 3
%
%       Then it asks:
%             -Model II [pure] (1) or mixed [III] (2):
%             For this example you must to put it after the colon, 1
%
%       Answer is:
%  Nested factor always is random. Here, the highest level of classification also is random.    
%  ------------------------------------------------------------------------------
%  SV              SS           df      MS          F        P       % Comp.var.
%  ------------------------------------------------------------------------------
%  Subgps.         2.420         8
%  Gps.            2.370         2     1.185    142.200   0.0000        91.69
%  Subgps(Gps.)    0.050         6     0.008      0.469   0.8156         0.00
%  Error           0.160         9     0.018                             8.31
%  Total           2.580        17
%  ------------------------------------------------------------------------------
%

%  Created by A. Trujillo-Ortiz and R. Hernandez-Walls
%             Facultad de Ciencias Marinas
%             Universidad Autonoma de Baja California
%             Apdo. Postal 453
%             Ensenada, Baja California
%             Mexico.
%             atrujo@uabc.mx
%  February 30, 2003.
%
%  To cite this file, this would be an appropriate format:
%  Trujillo-Ortiz, A. and R. Hernandez-Walls. (2003). nest1: Two-level nested analysis of variance 
%    design with equal sample sizes. A MATLAB file. [WWW document]. URL http://www.mathworks.com/
%    matlabcentral/fileexchange/loadFile.do?objectId=3065&objectType=file
%
%  References:
% 
%  Zar, J. H. (1999), Biostatistical Analysis. 4th. ed. 
%              New-Jersey:Prentice Hall pp. 305-308, 311.
%

if nargin < 1, 
    error('Requires at least one input arguments.'); 
end 

a=max(X(:,2)); %number of levels of the main factor.
b=max(X(:,3)); %number of levels of the nested factor.

fprintf('The number of levels of main factor are:%2i\n', a);
fprintf('The number of levels of nested factor are:%2i\n', b);
disp('     ')
      
indice=X(:,2);
for i=1:a
   Xe=find(indice==i);
   eval(['G' num2str(i) '=X(Xe,1);']);
end

C=(sum(X(:,1)))^2/length(X(:,1));  %Correction term.
SSTO=sum(X(:,1).^2)-C;  %Total sum of squares.
dfTO=length(X(:,1))-1;  %Total degrees of freedom.

%Procedure related to the subgroups (nested factor).
for i=1:a
   for j=1:b
      Xe=find((X(:,2)==i) & (X(:,3)==j));
      eval(['T' num2str(i) num2str(j) '=X(Xe,1);']);
   end
end

NSG=[];
for i=1:a
   for j=1:b
   eval(['n' num2str(i) num2str(j) '=length(T' num2str(i) num2str(j) ');'])
   eval(['x= n' num2str(i) num2str(j) ';'])
   NSG=[NSG,x];  
   end
end

SG=[];
for i=1:a
   for j=1:b
   eval(['x =((sum(T' num2str(i) num2str(j) ').^2)/length(T' num2str(i) num2str(j) '));'])
   SG=[SG,x];
   end
end

SSSG=sum(SG)-C;
dfSG=(a*b)-1;

%Procedure related to the within subgroups (error).
SSE=SSTO-SSSG;
dfE=dfTO-dfSG;
MSE=SSE/dfE;

%Procedure related to the groups (main factor).
G=[];
for i=1:a
   eval(['x =((sum(G' num2str(i) ').^2)/length(G' num2str(i) '));'])
   G=[G,x];
end
SSG=sum(G)-C;
dfG=a-1;
MSG=SSG/dfG;

%Procedure related to the among subgroups within groups.
SSSGG=SSSG-SSG;
dfSGG=dfSG-dfG;
MSSGG=SSSGG/dfSGG;

         mod=input ('Modelo II [pure] (1) or mixed [III] (2):');
         if (mod==1);
            disp('Nested factor always is random. Here, the highest level of classification also is random.')   
            FG=MSG/MSSGG;
            
            FSGG=MSSGG/MSE;
            PrG = 1 - fcdf(FG,dfG,dfSGG);  %Probability associated to the groups F statistic.
            PrSGG = 1 - fcdf(FSGG,dfSGG,dfE);  %Probability associated to the among subgroups within groups F statistic.
            %Variance components.
            s2=MSE;
            s2G=(MSG-MSSGG)/(NSG(1)*b);
            s2SGG=(MSSGG-MSE)/NSG(1);
            if s2 < 0
               s2 = 0;
            else
            end
            if s2G < 0
               s2G = 0;
            else
            end
            if s2SGG < 0
               s2SGG = 0;
            else
            end
           
            s2TO=s2+s2G+s2SGG;
            ps2=(s2/s2TO)*100;
            ps2G=(s2G/s2TO)*100;
            ps2SGG=(s2SGG/s2TO)*100;
            disp('     ')
            fprintf('------------------------------------------------------------------------------\n');
            disp('SV              SS           df      MS          F        P       % Comp.var.')
            fprintf('------------------------------------------------------------------------------\n');
            fprintf('Subgps.   %11.3f%10i\n\n',SSSG,dfSG);
            fprintf('Gps.      %11.3f%10i%10.3f%11.3f%9.4f%13.2f\n\n',SSG,dfG,MSG,FG,PrG,ps2G);
            fprintf('Subgps(Gps.)%9.3f%10i%10.3f%11.3f%9.4f%13.2f\n\n',SSSGG,dfSGG,MSSGG,FSGG,PrSGG,ps2SGG);
            fprintf('Error %15.3f%10i%10.3f%33.2f\n\n',SSE,dfE,MSE,ps2);
            fprintf('Total %15.3f%10i\n',SSTO,dfTO);
            fprintf('------------------------------------------------------------------------------\n');
            disp('     ')
         else
            
            disp('Nested factor always is random. Here, the highest level of classification is fixed.')
            FG=MSG/MSE;
            FSGG=MSSGG/MSE;
            PrG = 1 - fcdf(FG,dfG,dfE);  %Probability associated to the groups F-statistic.
            PrSGG = 1 - fcdf(FSGG,dfSGG,dfE);  %Probability associated to the among subgroups within groups F-statistic.
            disp('     ')
            fprintf('--------------------------------------------------------------\n');
            disp('SV                SS          df     MS          F        P')
            fprintf('--------------------------------------------------------------\n');
            fprintf('Subgps.   %11.3f%10i\n\n',SSSG,dfSG);
            fprintf('Gps.      %11.3f%10i%10.3f%11.3f%9.4f\n\n',SSG,dfG,MSG,FG,PrG);
            fprintf('Subgps(Gps.)%9.3f%10i%10.3f%11.3f%9.4f\n\n',SSSGG,dfSGG,MSSGG,FSGG,PrSGG);
            fprintf('Error %15.3f%10i%10.3f\n\n',SSE,dfE,MSE);
            fprintf('Total %15.3f%10i\n',SSTO,dfTO);
            fprintf('--------------------------------------------------------------\n');
            disp('     ')  
         end