function  [SS,df,MS,lbl] = anova(DV,IVs,names,fid)

% ANOVA -- SumSq, df, and MeanSq for full-factorial ANOVA design
%
% [SS,df,MS,lbl] = anova(DV,IVs,names,printp)
%
% DV is a column vector of the dependent variable. IVs is an NxK matrix 
% of independent factors. NAMES defaults to 'ABCD' (see PARTITION).
% Unless FID=0, the function prints the ANOVA via fprintf(fid,...).
%
% Algorithm:
%  dim = size(IVs,2) ; sets = partition(dim,[]) ;  % generate split indices
%  [SS,df] = sumsq(DV,IVs,sets) ;                  % sum-of-squares by "cells"
%  [SS,lbl]=partition(dim,SS,names);df=partition(dim,df);MS=SS./df %by factors
%
% Example: Within-subject design with three factors. Subjects=IV(:,1).
%  [SS,df,MS,lbl] = anova(DV,IVs,'SABC') ;
%  num=[2 3 4 ,  8  9 10 , 14]';den=[5 6 7 , 11 12 13 , 15]';
%  F = MS(num)./MS(den) ; p = 1-fcdf(F,df(num),df(den));
%  for k=1:7 fprintf('%s  %4d %4d   %6.2f  %f\n',...
%              lbl(num(k),:),df(num(k)),df(den(k)),F(k),p(k));end
%
% See also SUMSQ, PARTITION, FCDF, ANOVA1, ANOVA2.

% Original coding by Alex Petrov, Ohio State University
% $Revision: 1.0 $  $Date: 2002/12/20 21:21 $
%
% Part of the utils toolbox version 1.1 for MATLAB version 5 and up.
% http://alexpetrov.com/softw/utils/
% Copyright (c) Alexander Petrov 1999-2006, http://alexpetrov.com
% Please read the LICENSE and NO WARRANTY statement in ../utils_license.m

%--  Handle input arguments
if (nargin<3)  names = 'ABCDEDFGH' ; end    % default factor labels
if (nargin<4)  fid = 1 ; end       % print ANOVA table to STDOUT by default

%-- Generate split indices
dim = size(IVs,2) ;
sets = partition(dim,[]) ;

%-- Call SUMSQ to calculate "raw" SS and df
if (fid) fprintf(fid,'Partitioning the sum of squares...\n\n') ; end
[SS,df] = sumsq(DV,IVs,sets) ;

%-- Obtain interactions and error terms by subtraction
[SS,lbl] = partition(dim,SS,names) ;
df = partition(dim,df) ;

%-- Mean squares
MS = zeros(size(SS)) ;
idx = find(df>0) ;           % avoid division by 0 with saturated designs
MS(idx) = SS(idx)./df(idx) ;

%-- Plot the ANOVA table
eta2 = SS ./ SS(end) .* 100 ;
if (fid)
  fprintf(fid,'Source         SumSq   eta2[%%]     df        MeanSq\n') ;
  fprintf(fid,'---------------------------------------------------\n') ;
  for k=1:length(SS)
    fprintf(fid,'%s %15.3f   %6.2f  %6d  %12.4f\n',...
                lbl(k,:),SS(k),eta2(k),df(k),MS(k));
  end
  fprintf(fid,'---------------------------------------------------\n') ;
end


%--- Return SS, DF, MS, LBL
%%%%% End of ANOVA.M
