1 ## Copyright (C) 1995-2012 Kurt Hornik
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} {} spearman (@var{x})
21 ## @deftypefnx {Function File} {} spearman (@var{x}, @var{y})
22 ## @cindex Spearman's Rho
23 ## Compute Spearman's rank correlation coefficient @var{rho}.
25 ## For two data vectors @var{x} and @var{y}, Spearman's @var{rho} is the
26 ## correlation coefficient of the ranks of @var{x} and @var{y}.
28 ## If @var{x} and @var{y} are drawn from independent distributions,
29 ## @var{rho} has zero mean and variance @code{1 / (n - 1)}, and is
30 ## asymptotically normally distributed.
32 ## @code{spearman (@var{x})} is equivalent to @code{spearman (@var{x},
34 ## @seealso{ranks, kendall}
37 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
38 ## Description: Spearman's rank correlation rho
40 function rho = spearman (x, y = [])
42 if (nargin < 1 || nargin > 2)
46 if ( ! (isnumeric (x) || islogical (x))
47 || ! (isnumeric (y) || islogical (y)))
48 error ("spearman: X and Y must be numeric matrices or vectors");
51 if (ndims (x) != 2 || ndims (y) != 2)
52 error ("spearman: X and Y must be 2-D matrices or vectors");
60 rho = corr (ranks (x));
65 if (rows (x) != rows (y))
66 error ("spearman: X and Y must have the same number of observations");
68 rho = corr (ranks (x), ranks (y));
71 ## Restore class cleared by ranks
72 if (isa (x, 'single') || isa (y, 'single'))
82 %! assert (spearman (x,y), 1, 5*eps);
83 %! assert (spearman (x,-y), -1, 5*eps);
85 %!assert(spearman ([1 2 3], [-1 1 -2]), -0.5, 5*eps)
87 %% Test input validation
89 %!error spearman (1, 2, 3);
90 %!error spearman (['A'; 'B']);
91 %!error spearman (ones(1,2), {1, 2});
92 %!error spearman (ones (2,2,2));
93 %!error spearman (ones (2,2), ones (2,2,2));
94 %!error spearman (ones (2,2), ones (3,2));