7017
|
1 ## Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2002, 2004, 2005, |
|
2 ## 2006, 2007 Kurt Hornik |
3426
|
3 ## |
3922
|
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 |
7016
|
8 ## the Free Software Foundation; either version 3 of the License, or (at |
|
9 ## your option) any later version. |
3426
|
10 ## |
3922
|
11 ## Octave is distributed in the hope that it will be useful, but |
3200
|
12 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
3426
|
14 ## General Public License for more details. |
|
15 ## |
3200
|
16 ## You should have received a copy of the GNU General Public License |
7016
|
17 ## along with Octave; see the file COPYING. If not, see |
|
18 ## <http://www.gnu.org/licenses/>. |
3200
|
19 |
3367
|
20 ## -*- texinfo -*- |
|
21 ## @deftypefn {Function File} {} cov (@var{x}, @var{y}) |
6754
|
22 ## Compute covariance. |
|
23 ## |
3367
|
24 ## If each row of @var{x} and @var{y} is an observation and each column is |
4855
|
25 ## a variable, the (@var{i}, @var{j})-th entry of |
3367
|
26 ## @code{cov (@var{x}, @var{y})} is the covariance between the @var{i}-th |
6754
|
27 ## variable in @var{x} and the @var{j}-th variable in @var{y}. |
|
28 ## @iftex |
|
29 ## @tex |
|
30 ## $$ |
|
31 ## \sigma_{ij} = {1 \over N-1} \sum_{i=1}^N (x_i - \bar{x})(y_i - \bar{y}) |
|
32 ## $$ |
|
33 ## where $\bar{x}$ and $\bar{y}$ are the mean values of $x$ and $y$. |
|
34 ## @end tex |
|
35 ## @end iftex |
|
36 ## If called with one argument, compute @code{cov (@var{x}, @var{x})}. |
3367
|
37 ## @end deftypefn |
3200
|
38 |
5428
|
39 ## Author: KH <Kurt.Hornik@wu-wien.ac.at> |
3456
|
40 ## Description: Compute covariances |
3200
|
41 |
|
42 function c = cov (x, y) |
|
43 |
|
44 if (nargin < 1 || nargin > 2) |
6046
|
45 print_usage (); |
3200
|
46 endif |
|
47 |
|
48 if (rows (x) == 1) |
|
49 x = x'; |
|
50 endif |
|
51 n = rows (x); |
|
52 |
|
53 if (nargin == 2) |
|
54 if (rows (y) == 1) |
|
55 y = y'; |
|
56 endif |
|
57 if (rows (y) != n) |
3458
|
58 error ("cov: x and y must have the same number of observations"); |
3200
|
59 endif |
|
60 x = x - ones (n, 1) * sum (x) / n; |
|
61 y = y - ones (n, 1) * sum (y) / n; |
|
62 c = conj (x' * y / (n - 1)); |
|
63 elseif (nargin == 1) |
|
64 x = x - ones (n, 1) * sum (x) / n; |
|
65 c = conj (x' * x / (n - 1)); |
|
66 endif |
|
67 |
|
68 endfunction |
7411
|
69 |
|
70 %!test |
|
71 %! x = rand (10); |
|
72 %! cx1 = cov (x); |
|
73 %! cx2 = cov (x, x); |
7939
|
74 %! assert(size (cx1) == [10, 10] && size (cx2) == [10, 10] && norm(cx1-cx2) < 1e1*eps); |
7411
|
75 |
|
76 %!error cov (); |
|
77 |
|
78 %!error cov (1, 2, 3); |
|
79 |