]> Creatis software - CreaPhase.git/blob - octave_packages/m/statistics/base/zscore.m
update packages
[CreaPhase.git] / octave_packages / m / statistics / base / zscore.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} {} zscore (@var{x})
21 ## @deftypefnx {Function File} {} zscore (@var{x}, @var{dim})
22 ## If @var{x} is a vector, subtract its mean and divide by its standard
23 ## deviation.
24 ##
25 ## If @var{x} is a matrix, do the above along the first non-singleton
26 ## dimension.
27 ## If the optional argument @var{dim} is given, operate along this dimension.
28 ## @seealso{center}
29 ## @end deftypefn
30
31 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
32 ## Description: Subtract mean and divide by standard deviation
33
34 function z = zscore (x, dim)
35
36   if (nargin != 1 && nargin != 2)
37     print_usage ();
38   endif
39
40   if (! (isnumeric (x) || islogical (x)))
41     error ("zscore: X must be a numeric vector or matrix");
42   endif
43
44   nd = ndims (x);
45   sz = size (x);
46   if (nargin != 2)
47     ## Find the first non-singleton dimension.
48     (dim = find (sz > 1, 1)) || (dim = 1);
49   else
50     if (!(isscalar (dim) && dim == fix (dim))
51         || !(1 <= dim && dim <= nd))
52       error ("zscore: DIM must be an integer and a valid dimension");
53     endif
54   endif
55
56   n = sz(dim);
57   if (n == 0)
58     z = x;
59   else
60     x = center (x, dim); # center also promotes integer to double for next line
61     z = zeros (sz, class (x));
62     s = std (x, [], dim);
63     s(s==0) = 1;
64     z = bsxfun (@rdivide, x, s);
65   endif
66
67 endfunction
68
69
70 %!assert(zscore ([1,2,3]), [-1,0,1])
71 %!assert(zscore (single([1,2,3])), single([-1,0,1]))
72 %!assert(zscore (int8([1,2,3])), [-1,0,1])
73 %!assert(zscore (ones (3,2,2,2)), zeros (3,2,2,2))
74 %!assert(zscore ([2,0,-2;0,2,0;-2,-2,2]), [1,0,-1;0,1,0;-1,-1,1])
75
76 %% Test input validation
77 %!error zscore ()
78 %!error zscore (1, 2, 3)
79 %!error zscore (['A'; 'B'])
80 %!error zscore (1, ones(2,2))
81 %!error zscore (1, 1.5)
82 %!error zscore (1, 0)
83 %!error zscore (1, 3)
84