  yijk =[...
      65  68  56    74  69  73    65  67  72    81  76  77 ;...
      71  70  55    76  70  77    74  59  63    75  72  69 ;...
      63  64  65    79  80  77    70  61  64    77  79  74 ;...
      69  71  68    81  79  79    69  66  69    75  82  79 ;...
      73  75  70    72  68  68    73  71  70    80  78  66  ];
  
  a = 4;
  b = 3;
  n = 5;
  
  %matrices of means (y..., y_i.., y_ij.)
  yddd = mean(mean(yijk)) * ones(n, a*b)
  yijd = repmat(mean(yijk), n, 1)
  %yidd---------------------
      m=mean(yijk);
      mm=reshape(m', b, a);
      c=mean(mm);
      d=repmat(c',1,b);
      e=d';
  yidd = repmat(e(:)',n,1)

  
SST = sum(sum((yijk - yddd).^2) )   %2.3166e+003
SSA = sum(sum((yidd - yddd).^2) )   %1.0227e+003
SSB_A = sum(sum((yijd - yidd).^2) ) %295.0667
SSE = sum(sum((yijk - yijd).^2) )   %998.8


MSA = SSA/(a-1)           %340.9111
MSB_A = SSB_A/(a * (b-1)) %36.8833
MSE = SSE/(a * b * (n-1)) %20.8083


%A fixed B(A) fixed
FAfixed = MSA/MSE  
pa = 1- fcdf(FAfixed, a-1, a*b*(n-1))  


%A fixed B(A) random //// 0r A random B(A) random
FArand = MSA/MSB_A   %9.2430
pa = 1- fcdf(FArand, a-1, a*(b-1))  %0.0056

% 
FB_A = MSB_A/MSE  %1.7725
pb_a =  1- fcdf(FB_A,  a*(b-1), a*b*(n-1))  %0.1061

%Display bar a bar graph of anova table
H=figure;
set(H,'Position',[400 400 400 400]);
y=[0 0 1 1];
hold on
h1=fill([0 SST SST 0],y,'c');
y=y+1;
h2=fill([0 SSA SSA 0],y,'y');
h3=fill([0 SSB_A SSB_A 0]+SSA,y,'r');
h4=fill([0 SSE SSE 0]+SSA+SSB_A,y,'b');
hold off
legend([h2 h3 h4 h1],'SSA','SSB_A','SSE','SST','Location','SouthWest')
title('Sums of Squares')

%% solution using "anovan"; need to recode the data
%as row vectors.
 yijk =[...
      65  68  56    74  69  73    65  67  72    81  76  77 ...
      71  70  55    76  70  77    74  59  63    75  72  69 ...
      63  64  65    79  80  77    70  61  64    77  79  74 ...
      69  71  68    81  79  79    69  66  69    75  82  79 ...
      73  75  70    72  68  68    73  71  70    80  78  66  ];
  diet = repmat([1 1 1 2 2 2 3 3 3 4 4 4], 1, 5);
  animal = repmat([1 2 3],1, 20);
 
mynest=[0 0;1 0];    %for factors {1,2}, 2 nested in 1, matrix element (2,1) is 1.
%animals within diets are random, need to declare 'random',[2]
[p table stats]=...
anovan(yijk,{diet, animal},'nested',mynest,'random',[2],'varnames',{'diet','animal'})
    table
% Analysis of Variance
%   Source        	     Sum Sq.	 d.f.  	Mean Sq.	  F	         Prob>F
%   diet	                1022.7333	3	340.9111	9.243	   0.00560 
%   animal(diet)	 295.0667	 8	  36.8833	  1.7725	0.10609
%   Error	                  998.8	      48   	20.8083		
%   Total	                2316.6	     59			
% Constrained (Type III) sums of squares.
