changelog shortlog tags changeset files revisions annotate raw

scripts/statistics/base/cov.m

changeset 10289: 4b124317dc38
parent:f0c3d3fc4903
author: John W. Eaton <jwe@octave.org>
date: Tue Feb 09 20:58:55 2010 -0500 (40 minutes ago)
permissions: -rw-r--r--
description: base_properties::set_children: account for hidden children
1## Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2002, 2004, 2005,
2## 2006, 2007, 2008, 2009 Kurt Hornik
3##
4## This file is part of Octave.
5##
6## Octave is free software; you can redistribute it and/or modify it
7## under the terms of the GNU General Public License as published by
8## the Free Software Foundation; either version 3 of the License, or (at
9## your option) any later version.
10##
11## Octave is distributed in the hope that it will be useful, but
12## WITHOUT ANY WARRANTY; without even the implied warranty of
13## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14## General Public License for more details.
15##
16## You should have received a copy of the GNU General Public License
17## along with Octave; see the file COPYING. If not, see
18## <http://www.gnu.org/licenses/>.
19
20## -*- texinfo -*-
21## @deftypefn {Function File} {} cov (@var{x}, @var{y})
22## Compute covariance.
23##
24## If each row of @var{x} and @var{y} is an observation and each column is
25## a variable, the (@var{i}, @var{j})-th entry of
26## @code{cov (@var{x}, @var{y})} is the covariance between the @var{i}-th
27## variable in @var{x} and the @var{j}-th variable in @var{y}.
28## @tex
29## $$
30## \sigma_{ij} = {1 \over N-1} \sum_{i=1}^N (x_i - \bar{x})(y_i - \bar{y})
31## $$
32## where $\bar{x}$ and $\bar{y}$ are the mean values of $x$ and $y$.
33## @end tex
34## If called with one argument, compute @code{cov (@var{x}, @var{x})}.
35## @end deftypefn
36
37## Author: KH <Kurt.Hornik@wu-wien.ac.at>
38## Description: Compute covariances
39
40function c = cov (x, y)
41
42 if (nargin < 1 || nargin > 2)
43 print_usage ();
44 endif
45
46 if (rows (x) == 1)
47 x = x';
48 endif
49 n = rows (x);
50
51 if (nargin == 2)
52 if (rows (y) == 1)
53 y = y';
54 endif
55 if (rows (y) != n)
56 error ("cov: x and y must have the same number of observations");
57 endif
58 x = center (x, 1);
59 y = center (y, 1);
60 c = conj (x' * y / (n - 1));
61 elseif (nargin == 1)
62 x = center (x, 1);
63 c = conj (x' * x / (n - 1));
64 endif
65
66endfunction
67
68%!test
69%! x = rand (10);
70%! cx1 = cov (x);
71%! cx2 = cov (x, x);
72%! assert(size (cx1) == [10, 10] && size (cx2) == [10, 10] && norm(cx1-cx2) < 1e1*eps);
73
74%!error cov ();
75
76%!error cov (1, 2, 3);
77