function [chi2, df, pvalue, exp] = partialrxcxp(obs,partial)
% % 3D Contingency Table r x c x p for testing the independence
% %
% % Input:
% %   obs - r x c x p 3D array of observed frequencies
% %   partial - One of: p_rc, r_cp, c_pr. Choice p_rc checks that 
% %   page factor is independednt of row/column factors.
% %  
% % Output
% %    chi2 - statistics (approx distributed as chi-square with
% %                       (r-1)(c-1) degrees of freedom)
% %    df - degrees of freedom for chi^2.
% %    pvalue  - p - value
% %    exp -  3D array  of expected frequencies
% % Example of use: 
% obs= cat(3, [44 12; 28 22],[38 10; 20 18]);
% [chi2, df pvalue,exp]=partialrxcxp(obs,'r_cp')
% %------------------------------------------------------------

[r c p] = size(obs);
    rowsums = sum(sum(permute(obs, [3 2 1])));
    colsums = sum(sum(permute(obs, [3 1 2])));
    pagsums = sum(sum(obs));
    rowcolapse = sum( obs );
    colcolapse = sum( permute( obs, [2 1 3]));
    pagcolapse = sum( permute( obs, [3 1 2]));   
    n = sum(pagsums);
    if(partial == 'p_rc' | partial == 'p_cr' )
 for i = 1:r
     for j = 1:c
         for k=1:p
             exp(i,j,k)= pagcolapse(1, i,j)*pagsums(k)/n;
         end
     end
 end
 chi2 = sum(sum(sum( (obs - exp).^2 ./exp )));
 df = r*c*p - r*c - p + 1;
 pvalue = 1-chi2cdf(chi2, df);
    elseif (partial == 'r_pc' | partial == 'r_cp' )  
   for i = 1:r
     for j = 1:c
         for k=1:p
             exp(i,j,k)= rowcolapse(1,j,k)*rowsums(i)/n;
         end
     end
 end
 chi2 = sum(sum(sum( (obs - exp).^2 ./exp )));
 df = r*c*p - c*p - r + 1;
 pvalue = 1-chi2cdf(chi2, df);     
        elseif (partial == 'c_rp' | partial == 'c_pr')
     for i=1:r
                for j = 1:c
         for k=1:p
             exp(i,j,k)= colcolapse(1,i,k)*colsums(j)/n;
         end
     end
 end
 chi2 = sum(sum(sum( (obs - exp).^2 ./exp )));
 df = r*c*p - r*p - c + 1;
 pvalue = 1-chi2cdf(chi2, df); 
            else
                error('Try one of: p_rc, c_rp, or r_cp')
            end

 
%-------------------------------------------------------------------
% Copyright (C) 2009 by BVidakovic
% Ver 0.12   8/7/2009% 

