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} {} corrcoef (@var{x})
21 ## @deftypefnx {Function File} {} corrcoef (@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{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}.
30 ## {\rm corrcoef}(x,y) = {{\rm cov}(x,y) \over {\rm std}(x) {\rm std}(y)}
36 ## corrcoef(x,y) = cov(x,y)/(std(x)*std(y))
40 ## If called with one argument, compute @code{corrcoef (@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 = corrcoef (x, y = [])
51 persistent warned = false;
54 warning ("Octave:deprecated-function",
55 "corrcoef is not equivalent to Matlab and will be removed from a future version of Octave; for similar functionality see corr");
58 if (nargin < 1 || nargin > 2)
62 ## Input validation is done by cov.m. Don't repeat tests here
64 ## Special case, scalar is always 100% correlated with itself
66 if (isa (x, 'single'))
74 ## No check for division by zero error, which happens only when
75 ## there is a constant vector and should be rare.
78 s = std (x)' * std (y);
83 retval = c ./ (s * s');
91 %! cc1 = corrcoef (x);
92 %! cc2 = corrcoef (x, x);
93 %! assert (size (cc1) == [10, 10] && size (cc2) == [10, 10]);
94 %! assert (cc1, cc2, sqrt (eps));
99 %! assert (corrcoef (x,y), -1, 5*eps)
100 %! assert (corrcoef (x,flipud (y)), 1, 5*eps)
101 %! assert (corrcoef ([x, y]), [1 -1; -1 1], 5*eps)
104 %! x = single ([1:3]');
105 %! y = single ([3:-1:1]');
106 %! assert (corrcoef (x,y), single (-1), 5*eps)
107 %! assert (corrcoef (x,flipud (y)), single (1), 5*eps)
108 %! assert (corrcoef ([x, y]), single ([1 -1; -1 1]), 5*eps)
110 %!assert (corrcoef (5), 1);
111 %!assert (corrcoef (single(5)), single(1));
113 %% Test input validation
115 %!error corrcoef (1, 2, 3);
116 %!error corrcoef ([1; 2], ["A", "B"]);
117 %!error corrcoef (ones (2,2,2));
118 %!error corrcoef (ones (2,2), ones (2,2,2));