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 |
4852
|
50 function retval = median (a, dim) |
3200
|
51 |
4852
|
52 if (nargin != 1 && nargin != 2) |
|
53 usage ("median (a, dim)"); |
|
54 endif |
|
55 if (nargin < 2) |
|
56 dim = min (find (size (a) > 1)); |
|
57 if (isempty (dim)) |
|
58 dim = 1; |
|
59 endif |
3200
|
60 endif |
|
61 |
4852
|
62 sz = size (a); |
|
63 s = sort (a, dim); |
|
64 if (numel (a) > 1) |
|
65 if (numel (a) == sz(dim)) |
|
66 if (rem (sz(dim), 2) == 0) |
|
67 i = sz(dim) / 2; |
|
68 retval = (s(i) + s(i+1)) / 2; |
|
69 else |
|
70 i = ceil (sz(dim) /2); |
|
71 retval = s(i); |
|
72 endif |
3200
|
73 else |
4852
|
74 idx = cell (); |
|
75 nd = length (sz); |
|
76 for i = 1:nd |
|
77 idx{i} = 1:sz(i); |
|
78 endfor |
|
79 if (rem (sz(dim), 2) == 0) |
|
80 i = sz(dim) / 2; |
|
81 idx{dim} = i; |
|
82 retval = s(idx{:}); |
|
83 idx{dim} = i+1; |
|
84 retval = (retval + s(idx{:})) / 2; |
|
85 else |
|
86 idx{dim} = ceil (sz(dim) / 2); |
|
87 retval = s(idx{:}); |
|
88 endif |
3200
|
89 endif |
|
90 else |
|
91 error ("median: invalid matrix argument"); |
|
92 endif |
|
93 |
|
94 endfunction |