comparison extra/ver20/nanmedian.m @ 0:6b33357c7561 octave-forge

Initial revision
author pkienzle
date Wed, 10 Oct 2001 19:54:49 +0000
parents
children 143f3827b789
comparison
equal deleted inserted replaced
-1:000000000000 0:6b33357c7561
1 ## Copyright (C) 2001 Paul Kienzle
2 ##
3 ## This program is free software; you can redistribute it and/or modify
4 ## it under the terms of the GNU General Public License as published by
5 ## the Free Software Foundation; either version 2 of the License, or
6 ## (at your option) any later version.
7 ##
8 ## This program is distributed in the hope that it will be useful,
9 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 ## GNU General Public License for more details.
12 ##
13 ## You should have received a copy of the GNU General Public License
14 ## along with this program; if not, write to the Free Software
15 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16
17 ## v = nanmedian(X [, dim]);
18 ## nanmedian is identical to the median function except that NaN values are
19 ## ignored. If all values are NaN, the median is returned as NaN.
20 ## [Is this behaviour compatible?]
21 ##
22 ## See also: nanmin, nanmax, nansum, nanmean
23 function v = nanmedian (X, dim)
24 if nargin < 1 || nargin > 2
25 usage ("v = nanmean(X [, dim])");
26 else
27 if nargin == 1
28 if size(X,1) == 1
29 dim = 2;
30 else
31 dim = 1;
32 endif
33 endif
34 if (dim == 2) X = X.'; endif
35 dfi = do_fortran_indexing;
36 pzoi = prefer_zero_one_indexing;
37 unwind_protect
38 do_fortran_indexing = 1;
39 prefer_zero_one_indexing = 1;
40
41 ## Find lengths of datasets after excluding NaNs; valid datasets
42 ## are those that are not empty after you remove all the NaNs
43 n = size(X,1) - sum (isnan(X));
44 valid = find(n!=0);
45
46 ## Extract all non-empty datasets and sort, replacing NaN with Inf
47 ## so that the invalid elements go toward the ends of the columns
48 X (isnan(X)) = Inf;
49 X = sort ( X (:, valid) );
50
51 ## Determine the offset for each remaining column in single index mode
52 colidx = (0:size(X,2)-1)*size(X,1);
53
54 ## Assume the median for all datasets will be NaNs
55 v = NaN*ones(size(n));
56
57 ## Average the two central values of the sorted list to compute
58 ## the median, but only do so for valid rows. If the dataset
59 ## is odd length, the single central value will be used twice.
60 ## E.g.,
61 ## for n==5, ceil(2.5+0.4) is 3 and floor(2.5+0.6) is also 3
62 ## for n==6, ceil(3.0+0.4) is 4 and floor(3.0+0.6) is 3
63 v(valid) = ( X (colidx + floor(n(valid)./2+0.6)) ...
64 + X (colidx + ceil(n(valid)./2+0.4)) ) ./ 2;
65 unwind_protect_cleanup
66 do_fortran_indexing = dfi;
67 prefer_zero_one_indexing = pzoi;
68 end_unwind_protect
69 if (dim == 2) v = v.'; endif
70 endif
71 endfunction