function  [chi2, pvalue, expected, assoc ] = tablerxc(observed)
% Contingency Table r x c for testing the probabilities
%
% Input:
%   observed - r x c matrix of observations.
%  
% Output
%    chi2 - statistics (approx distributed as chi-square with
%                       (r-1)(c-1) degrees of freedom)
%    pvalue  - p - value
%    expected - matrix of expected probabilities
%    asoc - structure containing association measures: phi, 
%                C, and Cramer's V
% Example of use:
%    [chi2,pvalue,expected, assoc]=tablerxc([6 14 17 9; 30 32 17 3])
%------------------------------------------------------------
  [r c]=size(observed);                               %size of matrix
  n = sum(sum(observed));                       %total s. size
  columns = sum(observed);                    %col sums 1 x c
  rows = sum(observed')';                         %row sums r x 1
  expected = rows * columns ./ n;  %[r x c] matrix
  chi2 = sum(sum((expected - observed).^2./expected ));
  df=(r-1)*(c-1);
  pvalue = 1- chi2cdf(chi2, df);
  % measures of association
  if (df == 1)
  assoc.phi = sqrt(chi2/n);
  end
  assoc.C = sqrt(chi2/(n + chi2));
  assoc.V = sqrt(chi2/(n * (min(r,c)-1)));
%-------------------------------------------------------------------
% Copyright (C) 2002 by GaTech
% Ver 0.12    9/28/2002 
% Ver 0.2      7/15/2009
