clear all
close all

%model with interaction
clear all
close all
  disp('RandR -- Impedance3')
  set(0, 'DefaultAxesFontSize', 16);
  lw =2.5;  fs = 16;  msize = 10;




impedance = [...
     37 38 37 41 41 40 41 42 41 42 41 43 42 42 42 43 42 43  ...
     30 31 31 31 31 31 29 30 28 42 43 42 43 43 43 42 42 42  ...
     28 30 29 29 30 29 31 29 29 42 42 43 45 45 45 44 46 45  ...
     25 26 27 28 28 30 29 27 27 40 40 40 43 42 42 43 43 41  ...
     25 25 25 27 29 28 26 26 26 35 34 34 35 35 34 35 34 35]' ;

% forming part and operator vectors.
a = repmat([1:10],9,1);  part = a(:);
b = repmat([1:3], 3,1);  operator = repmat(b(:),10,1);

[p table stats terms] =  anovan( impedance,{part, operator},...
 'model','interaction','varnames',{'part','operator'} )

MSE = table{5,5} %0.5111
MSPO =table{4,5} %2.6951
MSO = table{3,5} %19.6333
MSP = table{2,5} %437.3284
p = stats.nlevels(1); o = stats.nlevels(2); n=length(impedance)/(p * o);

s2Part = (MSP - MSPO)/(o * n) %48.2926
s2Oper = (MSO - MSPO)/(p * n) %0.5646
s2PartOper = (MSPO - MSE)/n   %0.7280
s2 = MSE                      %0.5111
   
s2Repeat = s2  %0.5111
s2Repro = s2Oper + s2PartOper  %1.2926
s2Gage = s2Repeat + s2Repro    %1.8037
s2Tot = s2Gage  + s2Part       %50.0963

%percent variation due to part
ps2Part = s2Part/s2Tot  %0.9640

% signal-to-noise ratio; > 5 measuring system is capable
snr = sqrt( 2 * ps2Part/(1-ps2Part))  %7.3177
% snr rounded is NDC (number of distinct categories).
ndc = round(snr)  %7


% percent of R&R variability
prr = sqrt(s2Gage/s2Tot)  %0.1897

%MATLAB's built in function
gagerr(impedance,{part, operator},'model','interaction')

 
%   Source       Variance    %Variance   sigma   5.15*sigma  %5.15*sigma 
%   =====================================================================
%   Gage R&R       1.80         3.60     1.34     6.92         18.97 
%     Repeatab.    0.51         1.02     0.71     3.68         10.10 
%     Reproduc.    1.29         2.58     1.14     5.86         16.06 
%      Operator    0.56         1.13     0.75     3.87         10.62 
%      Part*Oper   0.73         1.45     0.85     4.39         12.05 
%   Part          48.29        96.40     6.95    35.79         98.18 
%   Total         50.10       100.00     7.08    36.45 
%   ---------------------------------------------------------------------
%               Number of distinct categories (NDC)    :  7
%               % of Gage R&R of total variations (PRR):  18.97



