3200
|
1 ## Copyright (C) 1996, 1997 John W. Eaton |
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
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 2, or (at your option) |
|
8 ## any later version. |
|
9 ## |
|
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. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
|
17 ## Software Foundation, 59 Temple Place - Suite 330, Boston, MA |
|
18 ## 02111-1307, USA. |
|
19 |
3367
|
20 ## -*- texinfo -*- |
|
21 ## @deftypefn {Function File} {} median (@var{x}) |
|
22 ## If @var{x} is a vector, compute the median value of the elements of |
|
23 ## @var{x}. |
|
24 ## @iftex |
|
25 ## @tex |
|
26 ## $$ |
|
27 ## {\rm median} (x) = |
|
28 ## \cases{x(\lceil N/2\rceil), & $N$ odd;\cr |
|
29 ## (x(N/2)+x(N/2+1))/2, & $N$ even.} |
|
30 ## $$ |
|
31 ## @end tex |
|
32 ## @end iftex |
|
33 ## @ifinfo |
|
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 ifinfo |
|
43 ## If @var{x} is a matrix, compute the median value for each |
|
44 ## column and return them in a row vector. |
|
45 ## @end deftypefn |
|
46 |
3200
|
47 ## See also: std, mean |
|
48 |
|
49 ## Author: jwe |
|
50 |
|
51 function retval = median (a) |
|
52 |
|
53 if (nargin != 1) |
|
54 usage ("median (a)"); |
|
55 endif |
|
56 |
|
57 [nr, nc] = size (a); |
|
58 s = sort (a); |
|
59 if (nr == 1 && nc > 0) |
|
60 if (rem (nc, 2) == 0) |
|
61 i = nc/2; |
|
62 retval = (s (i) + s (i+1)) / 2; |
|
63 else |
|
64 i = ceil (nc/2); |
|
65 retval = s (i); |
|
66 endif |
|
67 elseif (nr > 0 && nc > 0) |
|
68 if (rem (nr, 2) == 0) |
|
69 i = nr/2; |
|
70 retval = (s (i,:) + s (i+1,:)) / 2; |
|
71 else |
|
72 i = ceil (nr/2); |
|
73 retval = s (i,:); |
|
74 endif |
|
75 else |
|
76 error ("median: invalid matrix argument"); |
|
77 endif |
|
78 |
|
79 endfunction |