1 ## Copyright (C) 1995-2012 Kurt Hornik
2 ## Copyright (C) 2009 VZLU Prague
4 ## This file is part of Octave.
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.
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.
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/>.
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.
29 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
30 ## Description: Center by subtracting means
32 function retval = center (x, dim)
34 if (nargin != 1 && nargin != 2)
38 if (! (isnumeric (x) || islogical (x)))
39 error ("center: X must be a numeric vector or matrix");
49 ## Find the first non-singleton dimension.
50 (dim = find (sz > 1, 1)) || (dim = 1);
52 if (!(isscalar (dim) && dim == fix (dim))
53 || !(1 <= dim && dim <= nd))
54 error ("center: DIM must be an integer and a valid dimension");
63 retval = bsxfun (@minus, x, mean (x, dim));
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])
77 %% Test input validation
79 %!error center (1, 2, 3)
80 %!error center (1, ones(2,2))
81 %!error center (1, 1.5)