changelog shortlog tags changeset files revisions annotate raw

scripts/statistics/base/median.m

changeset 10289: 4b124317dc38
parent:f0c3d3fc4903
author: John W. Eaton <jwe@octave.org>
date: Tue Feb 09 20:58:55 2010 -0500 (63 minutes ago)
permissions: -rw-r--r--
description: base_properties::set_children: account for hidden children
1## Copyright (C) 1996, 1997, 1998, 1999, 2000, 2004, 2005, 2006, 2007,
2## 2008, 2009 John W. Eaton
3## Copyright (C) 2009 VZLU Prague
4##
5## This file is part of Octave.
6##
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.
11##
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.
16##
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/>.
20
21## -*- texinfo -*-
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
25## as
26## @tex
27## $$
28## {\rm median} (x) =
29## \cases{x(\lceil N/2\rceil), & $N$ odd;\cr
30## (x(N/2)+x(N/2+1))/2, & $N$ even.}
31## $$
32## @end tex
33## @ifnottex
34##
35## @example
36## @group
37## x(ceil(N/2)), N odd
38## median(x) =
39## (x(N/2) + x((N/2)+1))/2, N even
40## @end group
41## @end example
42## @end ifnottex
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.
46## @seealso{std, mean}
47## @end deftypefn
48
49## Author: jwe
50
51function retval = median (a, dim)
52
53 if (nargin != 1 && nargin != 2)
54 print_usage ();
55 endif
56 if (nargin < 2)
57 dim = [find(size (a) != 1, 1), 1](1); # First non-singleton dim.
58 endif
59
60 if (numel (a) > 0)
61 n = size (a, dim);
62 k = floor ((n+1) / 2);
63 if (mod (n, 2) == 1)
64 retval = nth_element (a, k, dim);
65 else
66 retval = mean (nth_element (a, k:k+1, dim), dim);
67 endif
68 else
69 error ("median: invalid matrix argument");
70 endif
71
72endfunction
73
74%!test
75%! x = [1, 2, 3, 4, 5, 6];
76%! x2 = x';
77%! y = [1, 2, 3, 4, 5, 6, 7];
78%! y2 = y';
79%!
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]));
84
85%!error median ();
86
87%!error median (1, 2, 3);
88