1 ## Copyright (C) 1995-2012 Kurt Hornik
3 ## This file is part of Octave.
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.
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.
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/>.
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
25 ## If @var{x} is a matrix, do the above along the first non-singleton
27 ## If the optional argument @var{dim} is given, operate along this dimension.
31 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
32 ## Description: Subtract mean and divide by standard deviation
34 function z = zscore (x, dim)
36 if (nargin != 1 && nargin != 2)
40 if (! (isnumeric (x) || islogical (x)))
41 error ("zscore: X must be a numeric vector or matrix");
47 ## Find the first non-singleton dimension.
48 (dim = find (sz > 1, 1)) || (dim = 1);
50 if (!(isscalar (dim) && dim == fix (dim))
51 || !(1 <= dim && dim <= nd))
52 error ("zscore: DIM must be an integer and a valid dimension");
60 x = center (x, dim); # center also promotes integer to double for next line
61 z = zeros (sz, class (x));
64 z = bsxfun (@rdivide, x, s);
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])
76 %% Test input validation
78 %!error zscore (1, 2, 3)
79 %!error zscore (['A'; 'B'])
80 %!error zscore (1, ones(2,2))
81 %!error zscore (1, 1.5)