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 |
3426
|
34 ## |
3367
|
35 ## @example |
|
36 ## @group |
|
37 ## x(ceil(N/2)), N odd |
3426
|
38 ## median(x) = |
3367
|
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 |
3408
|
46 ## @seealso{std and mean} |
3200
|
47 |
|
48 ## Author: jwe |
|
49 |
|
50 function retval = median (a) |
|
51 |
|
52 if (nargin != 1) |
|
53 usage ("median (a)"); |
|
54 endif |
|
55 |
|
56 [nr, nc] = size (a); |
|
57 s = sort (a); |
|
58 if (nr == 1 && nc > 0) |
|
59 if (rem (nc, 2) == 0) |
|
60 i = nc/2; |
|
61 retval = (s (i) + s (i+1)) / 2; |
|
62 else |
|
63 i = ceil (nc/2); |
|
64 retval = s (i); |
|
65 endif |
|
66 elseif (nr > 0 && nc > 0) |
|
67 if (rem (nr, 2) == 0) |
|
68 i = nr/2; |
|
69 retval = (s (i,:) + s (i+1,:)) / 2; |
|
70 else |
|
71 i = ceil (nr/2); |
|
72 retval = s (i,:); |
|
73 endif |
|
74 else |
|
75 error ("median: invalid matrix argument"); |
|
76 endif |
|
77 |
|
78 endfunction |