]> Creatis software - CreaPhase.git/blob - octave_packages/m/statistics/tests/chisquare_test_independence.m
update packages
[CreaPhase.git] / octave_packages / m / statistics / tests / chisquare_test_independence.m
1 ## Copyright (C) 1995-2012 Kurt Hornik
2 ##
3 ## This file is part of Octave.
4 ##
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
9 ##
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 ## General Public License for more details.
14 ##
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING.  If not, see
17 ## <http://www.gnu.org/licenses/>.
18
19 ## -*- texinfo -*-
20 ## @deftypefn {Function File} {[@var{pval}, @var{chisq}, @var{df}] =} chisquare_test_independence (@var{x})
21 ## Perform a chi-square test for independence based on the contingency
22 ## table @var{x}.  Under the null hypothesis of independence,
23 ## @var{chisq} approximately has a chi-square distribution with
24 ## @var{df} degrees of freedom.
25 ##
26 ## The p-value (1 minus the CDF of this distribution at chisq) of the
27 ## test is returned in @var{pval}.
28 ##
29 ## If no output argument is given, the p-value is displayed.
30 ## @end deftypefn
31
32 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
33 ## Description: Chi-square test for independence
34
35 function [pval, chisq, df] = chisquare_test_independence (x)
36
37   if (nargin != 1)
38     print_usage ();
39   endif
40
41   [r, s] = size (x);
42   df = (r - 1) * (s - 1);
43   n = sum (sum (x));
44   y = sum (x')' * sum (x) / n;
45   x = (x - y) .^2 ./ y;
46   chisq = sum (sum (x));
47   pval  = 1 - chi2cdf (chisq, df);
48
49   if (nargout == 0)
50     printf("  pval: %g\n", pval);
51   endif
52
53 endfunction