1 function y=var(x,opt,DIM,W)
2 % VAR calculates the variance.
4 % y = var(x [, opt[, DIM]])
5 % calculates the variance in dimension DIM
6 % the default DIM is the first non-single dimension
8 % opt 0: normalizes with N-1 [default]
13 % N: VAR of N-th dimension
14 % default or []: first DIMENSION, with more than 1 element
15 % W weights to compute weighted variance (default: [])
16 % if W=[], all weights are 1.
17 % number of elements in W must match size(x,DIM)
27 % - can deal with NaN's (missing values)
29 % - dimension argument
30 % - compatible to Matlab and Octave
32 % see also: MEANSQ, SUMSQ, SUMSKIPNAN, MEAN, RMS, STD,
34 % This program is free software; you can redistribute it and/or modify
35 % it under the terms of the GNU General Public License as published by
36 % the Free Software Foundation; either version 3 of the License, or
37 % (at your option) any later version.
39 % This program is distributed in the hope that it will be useful,
40 % but WITHOUT ANY WARRANTY; without even the implied warranty of
41 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
42 % GNU General Public License for more details.
44 % You should have received a copy of the GNU General Public License
45 % along with this program; If not, see <http://www.gnu.org/licenses/>.
47 % $Id: var.m 8223 2011-04-20 09:16:06Z schloegl $
48 % Copyright (C) 2000-2003,2006,2009,2010 by Alois Schloegl <alois.schloegl@gmail.com>
49 % This is part of the NaN-toolbox for Octave and Matlab
50 % http://pub.ist.ac.at/~schloegl/matlab/NaN/
60 elseif any(nargin==[2,3])
67 elseif (nargin==4) && (numel(opt)<2) && (numel(DIM)<2),
70 fprintf(1,'Error VAR: incorrect usage\n');
80 DIM = find(size(x)>1,1);
81 if isempty(DIM), DIM=1; end;
84 [y,n,ssq] = sumskipnan(x,DIM,W);
85 if all(ssq(:).*n(:) > 2*(y(:).^2)),
86 %% rounding error is neglectable
89 %% rounding error is not neglectable
92 if length(szy)<length(szx);
93 szy(length(szy)+1:length(szx)) = 1;
95 [y,n] = sumskipnan((x-repmat(y./n,szx./szy)).^2,DIM,W);
99 n = max(n-1,0); % in case of n=0 and n=1, the (biased) variance, STD and STE are INF
101 y = y./n; % normalize