1 ## Copyright (C) 1996-2012 John W. Eaton
3 ## This file is part of Octave.
5 ## Octave is free software; you can redistribute it and/or modify it
6 ## under the terms of the GNU General Public License as published by
7 ## the Free Software Foundation; either version 3 of the License, or (at
8 ## your option) any later version.
10 ## Octave is distributed in the hope that it will be useful, but
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ## General Public License for more details.
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING. If not, see
17 ## <http://www.gnu.org/licenses/>.
20 ## @deftypefn {Function File} {} corr (@var{x})
21 ## @deftypefnx {Function File} {} corr (@var{x}, @var{y})
22 ## Compute matrix of correlation coefficients.
24 ## If each row of @var{x} and @var{y} is an observation and each column is
25 ## a variable, then the @w{(@var{i}, @var{j})-th} entry of
26 ## @code{corr (@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}.
30 ## {\rm corr}(x,y) = {{\rm cov}(x,y) \over {\rm std}(x) {\rm std}(y)}
36 ## corr (x,y) = cov (x,y) / (std (x) * std (y))
40 ## If called with one argument, compute @code{corr (@var{x}, @var{x})},
41 ## the correlation between the columns of @var{x}.
45 ## Author: Kurt Hornik <hornik@wu-wien.ac.at>
46 ## Created: March 1993
49 function retval = corr (x, y = [])
51 if (nargin < 1 || nargin > 2)
55 ## Input validation is done by cov.m. Don't repeat tests here
57 ## Special case, scalar is always 100% correlated with itself
59 if (isa (x, 'single'))
67 ## No check for division by zero error, which happens only when
68 ## there is a constant vector and should be rare.
71 s = std (x)' * std (y);
76 retval = c ./ (s * s');
86 %! assert (size (cc1) == [10, 10] && size (cc2) == [10, 10]);
87 %! assert (cc1, cc2, sqrt (eps));
92 %! assert (corr (x,y), -1, 5*eps)
93 %! assert (corr (x,flipud (y)), 1, 5*eps)
94 %! assert (corr ([x, y]), [1 -1; -1 1], 5*eps)
97 %! x = single ([1:3]');
98 %! y = single ([3:-1:1]');
99 %! assert (corr (x,y), single (-1), 5*eps)
100 %! assert (corr (x,flipud (y)), single (1), 5*eps)
101 %! assert (corr ([x, y]), single ([1 -1; -1 1]), 5*eps)
103 %!assert (corr (5), 1);
104 %!assert (corr (single(5)), single(1));
106 %% Test input validation
108 %!error corr (1, 2, 3);
109 %!error corr ([1; 2], ["A", "B"]);
110 %!error corr (ones (2,2,2));
111 %!error corr (ones (2,2), ones (2,2,2));