]> Creatis software - CreaPhase.git/blob - octave_packages/m/statistics/base/center.m
update packages
[CreaPhase.git] / octave_packages / m / statistics / base / center.m
1 ## Copyright (C) 1995-2012 Kurt Hornik
2 ## Copyright (C) 2009 VZLU Prague
3 ##
4 ## This file is part of Octave.
5 ##
6 ## Octave is free software; you can redistribute it and/or modify it
7 ## under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 3 of the License, or (at
9 ## your option) any later version.
10 ##
11 ## Octave is distributed in the hope that it will be useful, but
12 ## WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 ## General Public License for more details.
15 ##
16 ## You should have received a copy of the GNU General Public License
17 ## along with Octave; see the file COPYING.  If not, see
18 ## <http://www.gnu.org/licenses/>.
19
20 ## -*- texinfo -*-
21 ## @deftypefn  {Function File} {} center (@var{x})
22 ## @deftypefnx {Function File} {} center (@var{x}, @var{dim})
23 ## If @var{x} is a vector, subtract its mean.
24 ## If @var{x} is a matrix, do the above for each column.
25 ## If the optional argument @var{dim} is given, operate along this dimension.
26 ## @seealso{zscore}
27 ## @end deftypefn
28
29 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
30 ## Description: Center by subtracting means
31
32 function retval = center (x, dim)
33
34   if (nargin != 1 && nargin != 2)
35     print_usage ();
36   endif
37
38   if (! (isnumeric (x) || islogical (x)))
39     error ("center: X must be a numeric vector or matrix");
40   endif
41
42   if (isinteger (x))
43     x = double (x);
44   endif
45
46   nd = ndims (x);
47   sz = size (x);
48   if (nargin != 2)
49     ## Find the first non-singleton dimension.
50     (dim = find (sz > 1, 1)) || (dim = 1);
51   else
52     if (!(isscalar (dim) && dim == fix (dim))
53         || !(1 <= dim && dim <= nd))
54       error ("center: DIM must be an integer and a valid dimension");
55     endif
56   endif
57
58   n = sz(dim);
59
60   if (n == 0)
61     retval = x;
62   else
63     retval = bsxfun (@minus, x, mean (x, dim));
64   endif
65
66 endfunction
67
68 %!assert(center ([1,2,3]), [-1,0,1])
69 %!assert(center (single([1,2,3])), single([-1,0,1]))
70 %!assert(center (int8 ([1,2,3])), [-1,0,1])
71 %!assert(center (logical ([1, 0, 0, 1])), [0.5, -0.5, -0.5, 0.5])
72 %!assert(center (ones (3,2,0,2)), zeros (3,2,0,2))
73 %!assert(center (ones (3,2,0,2, 'single')), zeros (3,2,0,2, 'single'))
74 %!assert(center (magic (3)), [3,-4,1;-2,0,2;-1,4,-3])
75 %!assert(center ([1 2 3; 6 5 4], 2), [-1 0 1; 1 0 -1])
76
77 %% Test input validation
78 %!error center ()
79 %!error center (1, 2, 3)
80 %!error center (1, ones(2,2))
81 %!error center (1, 1.5)
82 %!error center (1, 0)
83 %!error center (1, 3)