%% Quiz5  Fall 2011, Part 1
%
% Mimic this example either with some real data or some imaginary scenario/data. 
% You may want to change some of the parameters such as number of subjects,
% or number of levels in factors, or to add or omit a factor.
% Use MATLAB's 'publish' command to produce output.
% ----------------------------------------------------------------------------------
%
% Assume that there are 2 experimental conditions {1,2} and you recruit 4 subjects, two for each of the conditions.
% Denote subjects {11, 12} for condition 1 and {21, 22} for condition 2.
% Assume that each subject gives a measure for two factors A and B with two levels each.
% Thus the design is repeated measures over A and B, however, the subjects are different for conditions 1 and 2.
% 
% In this example, matrix 'data' has five columns: 'measurement', 'condition', 'factorA', 'factorB', and 'subjects'.
% -----------------------------------------------------------------------------------
 close all force
 clear all
data =      [ 21.4   1 1 1 11
              22.9   1 1 1 12
              19.7   1 1 2 11
              21.9   1 1 2 12
              24.1   1 2 1 11
              22.5   1 2 1 12
              19.9   1 2 2 11
              21.9   1 2 2 12
              19.1   2 1 1 21
              21.2   2 1 1 22
              18.8   2 1 2 21
              19.9   2 1 2 22
              21.2   2 2 1 21
              17.6   2 2 1 22
              18.2   2 2 2 21
              16.0   2 2 2 22];
measurement = data(:,1);
condition = data(:,2); 
factorA = data(:,3); 
factorB = data(:,4);
subjects = data(:,5);
% 
% Subjects are not crossed with condition, rather, they are nested within the condition.
% this is communicated to MATLAB by 'mynest' matrix where the entry (4,1) is 1,
% meaning that 4 (subjects) is nested in 1 (condition).

mynest = [0 0 0 0; 
          0 0 0 0; 
          0 0 0 0; 
          1 0 0 0];  
% 
% Also, 'subject' is a random factor, "'random', 4" 
% We would like to test all main effects (condition, factorA, factorB, subjects)
% as well as the interaction of factors A and B. This is communicated to MATLAB
% by model matrix 'mymodel'. 
mymodel =[0 0 0 0;   %intercept effect
          1 0 0 0;   %condition effect
          0 1 0 0;   %factorA  effect
          0 0 1 0;   %factorB effect
          0 0 0 1;   %subject effect
          0 1 1 0];  %factorA * factorB effect (interaction)
     
anovan(measurement, {condition, factorA, factorB, subjects},...
'random', [4],...
'nested', mynest,...
'varnames', {'condition', 'A', 'B', 'subjects'},...
'model', mymodel);
