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} {} var (@var{x})
21 ## @deftypefnx {Function File} {} var (@var{x}, @var{opt})
22 ## @deftypefnx {Function File} {} var (@var{x}, @var{opt}, @var{dim})
23 ## Compute the variance of the elements of the vector @var{x}.
26 ## {\rm var} (x) = \sigma^2 = {\sum_{i=1}^N (x_i - \bar{x})^2 \over N - 1}
28 ## where $\bar{x}$ is the mean value of $x$.
34 ## var (x) = 1/(N-1) SUM_i (x(i) - mean(x))^2
39 ## If @var{x} is a matrix, compute the variance for each column
40 ## and return them in a row vector.
42 ## The argument @var{opt} determines the type of normalization to use.
47 ## normalize with @math{N-1}, provides the best unbiased estimator of the
51 ## normalizes with @math{N}, this provides the second moment around the mean
54 ## If the optional argument @var{dim} is given, operate along this dimension.
55 ## @seealso{cov, std, skewness, kurtosis, moment}
58 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
59 ## Description: Compute variance
61 function retval = var (x, opt = 0, dim)
63 if (nargin < 1 || nargin > 3)
67 if (! (isnumeric (x) || islogical (x)))
68 error ("var: X must be a numeric vector or matrix");
74 if (opt != 0 && opt != 1)
75 error ("var: normalization OPT must be 0 or 1");
81 ## Find the first non-singleton dimension.
82 (dim = find (sz > 1, 1)) || (dim = 1);
84 if (!(isscalar (dim) && dim == fix (dim))
85 || !(1 <= dim && dim <= nd))
86 error ("var: DIM must be an integer and a valid dimension");
92 if (isa (x, 'single'))
93 retval = zeros (sz, 'single');
97 elseif (numel (x) > 0)
98 retval = sumsq (center (x, dim), dim) / (n - 1 + opt);
100 error ("var: X must not be empty");
106 %!assert(var (13), 0);
107 %!assert(var (single(13)), single(0));
108 %!assert(var ([1,2,3]), 1);
109 %!assert(var ([1,2,3], 1), 2/3, eps);
110 %!assert(var ([1,2,3], [], 1), [0,0,0]);
112 %% Test input validation
114 %!error var (1,2,3,4)
115 %!error var (['A'; 'B'])