changelog shortlog tags changeset files revisions annotate raw

scripts/statistics/base/corrcoef.m

changeset 10289: 4b124317dc38
parent:f0c3d3fc4903
author: John W. Eaton <jwe@octave.org>
date: Tue Feb 09 20:58:55 2010 -0500 (41 minutes ago)
permissions: -rw-r--r--
description: base_properties::set_children: account for hidden children
1## Copyright (C) 1996, 1997, 1998, 1999, 2004, 2005, 2006, 2007, 2008, 2009
2## John W. Eaton
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} {} corrcoef (@var{x}, @var{y})
22## Compute correlation.
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{corrcoef (@var{x}, @var{y})} is the correlation between the
27## @var{i}-th variable in @var{x} and the @var{j}-th variable in @var{y}.
28##
29## @tex
30## $$
31## {\rm corrcoef}(x,y) = {{\rm cov}(x,y) \over {\rm std}(x) {\rm std}(y)}
32## $$
33## @end tex
34## @ifnottex
35## @example
36## corrcoef(x,y) = cov(x,y)/(std(x)*std(y))
37## @end example
38## @end ifnottex
39##
40## If called with one argument, compute @code{corrcoef (@var{x}, @var{x})}.
41## @end deftypefn
42
43## Author: Kurt Hornik <hornik@wu-wien.ac.at>
44## Created: March 1993
45## Adapted-By: jwe
46
47function retval = corrcoef (x, y)
48
49 if (nargin < 1 || nargin > 2)
50 print_usage ();
51 endif
52
53 if (nargin == 2)
54 c = cov (x, y);
55 s = std (x)' * std (y);
56 retval = c ./ s;
57 elseif (nargin == 1)
58 c = cov (x);
59 s = reshape (sqrt (diag (c)), 1, columns (c));
60 retval = c ./ (s' * s);
61 endif
62
63endfunction
64
65%!test
66%! x = rand (10);
67%! cc1 = corrcoef (x);
68%! cc2 = corrcoef (x, x);
69%! assert((size (cc1) == [10, 10] && size (cc2) == [10, 10]
70%! && abs (cc1 - cc2) < sqrt (eps)));
71
72%!error corrcoef ();
73
74%!error corrcoef (1, 2, 3);
75