Home > wafo > wstats > var.m

# var

Variance

y = var(x, dim)

## DESCRIPTION

``` VAR  Variance

CALL: v = var(X,dim);

v  = Sample variance (second central moment)
X  = data vector or matrix
dim = dimension to sum across. (default 1'st non-singleton dimension of X)

Example:
R = wgumbrnd(2,2,[],100,2);
var(R)

## CROSS-REFERENCE INFORMATION

This function calls:
 class Create object or return object class. error Display message and abort function. isequal True if arrays are numerically equal. isscalar True for scalar input. nan Not-a-Number.
This function is called by:
 dist2dfit Parameter estimates for DIST2D data. emem Extended Maximum Entropy Method

## SOURCE CODE

```001 function y = var(x, dim)
002 %VAR  Variance
003 %
004 %   CALL: v = var(X,dim);
005 %
006 %     v  = Sample variance (second central moment)
007 %     X  = data vector or matrix
008 %   dim = dimension to sum across. (default 1'st non-singleton dimension of X)
009 %
010 % Example:
011 %    R = wgumbrnd(2,2,[],100,2);
012 %   var(R)
013 %
015
016
017
018
019 if nargin < 2
020     % The output size for [] is a special case when DIM is not given.
021     if isequal(x,[]), y = NaN(class(x)); return; end
022
023     % Figure out which dimension sum will work along.
024     dim = find(size(x) ~= 1, 1);
025     if isempty(dim), dim = 1; end
026 end
027 n = size(x,dim);
028
029 % Will replicate out the mean of X to the same size as X.
030 tile = ones(1,max(ndims(x),dim)); tile(dim) = n;
031
032 % Unweighted variance
033 if 1 %isequal(w,0) || isequal(w,1)
034     if  n > 1
035         % The unbiased estimator: divide by (n-1).  Can't do this
036         % when n == 0 or 1.
037         denom = n - 1;
038     else
039         % The biased estimator: divide by n.
040         denom = n; % n==0 => return NaNs, n==1 => return zeros
041     end
042
043     if n > 0
044         xbar = sum(x, dim) ./ n;
045         if isscalar(xbar)
046             x0 = x - xbar;
047         else
048             x0 = x - repmat(xbar, tile);
049         end
050     else % prevent redundant divideByZero warnings
051         x0 = x;
052     end
053     y = sum(abs(x0).^2, dim) ./ denom; % abs guarantees a real result
054
055 else
056     error('MATLAB:var:invalidWgts','W must be a vector of nonnegative weights, or a scalar 0 or 1.');
057 end
058 %v = std(varargin{:}).^2;
059 return
060```

Mathematical Statistics
Centre for Mathematical Sciences
Lund University with Lund Institute of Technology

Comments or corrections to the WAFO group

Generated on Thu 06-Oct-2005 02:21:16 for WAFO by m2html © 2003