]> Creatis software - CreaPhase.git/blob - octave_packages/m/statistics/base/table.m
update packages
[CreaPhase.git] / octave_packages / m / statistics / base / table.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{t}, @var{l_x}] =} table (@var{x})
21 ## @deftypefnx {Function File} {[@var{t}, @var{l_x}, @var{l_y}] =} table (@var{x}, @var{y})
22 ## Create a contingency table @var{t} from data vectors.  The @var{l_x} and
23 ## @var{l_y} vectors are the corresponding levels.
24 ##
25 ## Currently, only 1- and 2-dimensional tables are supported.
26 ## @end deftypefn
27
28 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
29 ## Description: Cross tabulation
30
31 function [t, v, w] = table (x, y)
32
33   if (nargin < 1 || nargin > 2)
34     print_usage ();
35   endif
36
37   if (nargin == 1)
38     if (!isnumeric (x) || !isvector (x))
39       error ("table: X must be a numeric vector");
40     endif
41     v = unique (x);
42     for i = 1 : length (v)
43       t(i) = sum (x == v(i) | isnan (v(i)) * isnan (x));
44     endfor
45   elseif (nargin == 2)
46     if (! (   isvector (x) && isnumeric (x)
47            && isvector (y) && isnumeric (y)
48            && (length (x) == length (y))))
49       error ("table: X and Y must be numeric vectors of the same length");
50     endif
51     v = unique (x);
52     w = unique (y);
53     for i = 1 : length (v)
54       for j = 1 : length (w)
55         t(i,j) = sum ((x == v(i) | isnan (v(i)) * isnan (x)) &
56                       (y == w(j) | isnan (w(j)) * isnan (y)));
57       endfor
58     endfor
59   endif
60
61 endfunction
62
63
64 %% Test input validation
65 %!error table ()
66 %!error table (1, 2, 3)
67 %!error table (ones (2))
68 %!error table ([true true])
69 %!error table (ones (2,1), true (2,1))
70 %!error table (true (2,1), ones (2,1))
71 %!error table (ones (2,2), ones (2,1))
72 %!error table (ones (2,1), ones (2,2))
73 %!error table (ones (2,1), ones (3,1))