1## Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2005, 2006, 2007,
2## 2008, 2009 John W. Eaton
3## Copyright (C) 2009 VZLU Prague
5## This file is part of Octave.
7## Octave is free software; you can redistribute it and/or modify it
8## under the terms of the GNU General Public License as published by
9## the Free Software Foundation; either version 3 of the License, or (at
10## your option) any later version.
12## Octave is distributed in the hope that it will be useful, but
13## WITHOUT ANY WARRANTY; without even the implied warranty of
14## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15## General Public License for more details.
17## You should have received a copy of the GNU General Public License
18## along with Octave; see the file COPYING. If not, see
19## <http://www.gnu.org/licenses/>.
22## @deftypefn {Function File} {} median (@var{x}, @var{dim})
23## If @var{x} is a vector, compute the median value of the elements of
24## @var{x}. If the elements of @var{x} are sorted, the median is defined
29## \cases{x(\lceil N/2\rceil), & $N$ odd;\cr
30## (x(N/2)+x(N/2+1))/2, & $N$ even.}
39## (x(N/2) + x((N/2)+1))/2, N even
43## If @var{x} is a matrix, compute the median value for each
44## column and return them in a row vector. If the optional @var{dim}
45## argument is given, operate along this dimension.
51function retval = median (a, dim)
53 if (nargin != 1 && nargin != 2)
57 dim = [find(size (a) != 1, 1), 1](1); # First non-singleton dim.
62 k = floor ((n+1) / 2);
64 retval = nth_element (a, k, dim);
66 retval = mean (nth_element (a, k:k+1, dim), dim);
69 error ("median: invalid matrix argument");
75%! x = [1, 2, 3, 4, 5, 6];
77%! y = [1, 2, 3, 4, 5, 6, 7];
80%! assert((median (x) == median (x2) && median (x) == 3.5
81%! && median (y) == median (y2) && median (y) == 4
82%! && median ([x2, 2*x2]) == [3.5, 7]
83%! && median ([y2, 3*y2]) == [4, 12]));
87%!error median (1, 2, 3);