1 ## Copyright (C) 2001 Paul Kienzle <pkienzle@users.sf.net>
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
17 ## @deftypefn {Function File} @var{v} = nanmedian (@var{x})
18 ## @deftypefnx{Function File} @var{v} = nanmedian (@var{x}, @var{dim})
19 ## Compute the median of data while ignoring NaN values.
21 ## This function is identical to the @code{median} function except that NaN values
22 ## are ignored. If all values are NaN, the median is returned as NaN.
24 ## @seealso{median, nanmin, nanmax, nansum, nanmean}
27 function v = nanmedian (X, varargin)
28 if nargin < 1 || nargin > 2
32 dim = min(find(size(X)>1));
33 if isempty(dim), dim=1; endif;
40 ## Find lengths of datasets after excluding NaNs; valid datasets
41 ## are those that are not empty after you remove all the NaNs
42 n = sz(dim) - sum (isnan(X),varargin{:});
44 ## When n is equal to zero, force it to one, so that median
45 ## picks up a NaN value below
48 ## Sort the datasets, with the NaN going to the end of the data
49 X = sort (X, varargin{:});
51 ## Determine the offset for each column in single index mode
52 colidx = reshape((0:(prod(sz) / sz(dim) - 1)), size(n));
53 colidx = floor(colidx / prod(sz(1:dim-1))) * prod(sz(1:dim)) + ...
54 mod(colidx,prod(sz(1:dim-1)));
55 stride = prod(sz(1:dim-1));
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.
61 ## for n==5, ceil(2.5+0.5) is 3 and floor(2.5+0.5) is also 3
62 ## for n==6, ceil(3.0+0.5) is 4 and floor(3.0+0.5) is 3
63 ## correction made for stride of data "stride*ceil(2.5-0.5)+1"
64 v = (X(colidx + stride*ceil(n./2-0.5) + 1) + ...
65 X(colidx + stride*floor(n./2-0.5) + 1)) ./ 2;
67 error ("nanmedian: invalid matrix argument");