1 ## Copyright (C) 1996-2012 John W. Eaton
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} {} std (@var{x})
21 ## @deftypefnx {Function File} {} std (@var{x}, @var{opt})
22 ## @deftypefnx {Function File} {} std (@var{x}, @var{opt}, @var{dim})
23 ## Compute the standard deviation of the elements of the vector @var{x}.
26 ## {\rm std} (x) = \sigma = \sqrt{{\sum_{i=1}^N (x_i - \bar{x})^2 \over N - 1}}
28 ## where $\bar{x}$ is the mean value of $x$ and $N$ is the number of elements.
34 ## std (x) = sqrt ( 1/(N-1) SUM_i (x(i) - mean(x))^2 )
39 ## where @math{N} is the number of elements.
42 ## If @var{x} is a matrix, compute the standard deviation for
43 ## each column and return them in a row vector.
45 ## The argument @var{opt} determines the type of normalization to use.
50 ## normalize with @math{N-1}, provides the square root of the best unbiased
51 ## estimator of the variance [default]
54 ## normalize with @math{N}, this provides the square root of the second
55 ## moment around the mean
58 ## If the optional argument @var{dim} is given, operate along this dimension.
59 ## @seealso{var, range, iqr, mean, median}
64 function retval = std (x, opt = 0, dim)
66 if (nargin < 1 || nargin > 3)
70 if (! (isnumeric (x) || islogical (x)))
71 error ("std: X must be a numeric vector or matrix");
77 if (opt != 0 && opt != 1)
78 error ("std: normalization OPT must be 0 or 1");
84 ## Find the first non-singleton dimension.
85 (dim = find (sz > 1, 1)) || (dim = 1);
87 if (!(isscalar (dim) && dim == fix (dim))
88 || !(1 <= dim && dim <= nd))
89 error ("std: DIM must be an integer and a valid dimension");
94 if (n == 1 || isempty (x))
95 if (isa (x, 'single'))
96 retval = zeros (sz, 'single');
101 retval = sqrt (sumsq (center (x, dim), dim) / (n - 1 + opt));
110 %! assert(std (x) == [0, 0]);
111 %! assert(std (y), sqrt (2), sqrt (eps));
112 %! assert(std (x, 0, 2), zeros (10, 1));
114 %!assert(std (ones (3, 1, 2), 0, 2), zeros (3, 1, 2));
115 %!assert(std ([1 2], 0), sqrt(2)/2, 5*eps);
116 %!assert(std ([1 2], 1), 0.5, 5*eps);
118 %!assert(std(single(1)), single(0));
119 %!assert(std([]), []);
120 %!assert(std(ones (1,3,0,2)), ones (1,3,0,2));
122 %% Test input validation
124 %!error std (1, 2, 3, 4);
125 %!error std (['A'; 'B'])