chi2cont.m 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. function [h,p,X2] = chi2cont(x,varargin)
  2. % chi2cont chi-square test of contingency table
  3. % h = chi2cont(x) performs a chi-square test on the data in the
  4. % m-by-n contingency table x. The null hypothesis is that there is no difference
  5. % in the row variable distribution ('outcomes') between the columns
  6. % ('treatments'). The result of the test is returned in h. h=1 indicates
  7. % a rejection of the null hypothesis at the 5% significance level.h=0
  8. % indicates that the null hypothesis can not be rejected at the 5%
  9. % significance level.
  10. %
  11. % h = chi2cont(x,alpha) performs the test at the (100*alpha)%
  12. % significance level. The default when unspecified is alpha=0.05;
  13. %
  14. % [h,p] = chi2cont(...) returns the p value of the test. The p value is
  15. % the probability, under the null hypothesis, of observing a value as
  16. % extreme or more extreme of the chi-square test statistic.
  17. %
  18. % [h,p,X2] = chi2cont(...) returns the chi-square test statistic.
  19. %
  20. % Reference http://www.psychstat.missouristate.edu/introbook/sbk28m.htm
  21. %
  22. % Mark Snaterse, January 22 2014
  23. if isempty(varargin)
  24. alpha = 0.05;
  25. elseif nargin>1
  26. error('Too many input arguments')
  27. else
  28. alpha = varargin{1};
  29. end
  30. % Compute expectation and chi-square statistic, and determine p value.
  31. e = sum(x,2)*sum(x)/sum(x(:));
  32. X2 = (x-e).^2./e;
  33. X2 = sum(X2(:));
  34. df = prod(size(x)-[1 1]);
  35. p = 1-chi2cdf(X2,df);
  36. h = double(p<=alpha);