]> Creatis software - CreaPhase.git/blob - octave_packages/nan-2.5.5/trimean.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / nan-2.5.5 / trimean.m
1 function y=trimean(x,DIM)
2 % TRIMEAN yields the weighted mean of the median and the quartiles
3 %    m = TRIMEAN(y).
4 %
5 % The trimean is  m = (Q1+2*MED+Q3)/4
6 %    with quartile Q1 and Q3 and median MED   
7 %
8 % N-dimensional data is supported
9
10 % REFERENCES:
11 % [1] http://mathworld.wolfram.com/Trimean.html
12
13
14 %    This program is free software; you can redistribute it and/or modify
15 %    it under the terms of the GNU General Public License as published by
16 %    the Free Software Foundation; either version 2 of the License, or
17 %    (at your option) any later version.
18 %
19 %    This program is distributed in the hope that it will be useful,
20 %    but WITHOUT ANY WARRANTY; without even the implied warranty of
21 %    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 %    GNU General Public License for more details.
23 %
24 %    You should have received a copy of the GNU General Public License
25 %    along with this program; If not, see <http://www.gnu.org/licenses/>.
26
27 %       $Id: trimean.m 9601 2012-02-09 14:14:36Z schloegl $
28 %       Copyright (C) 1996-2003,2009,2010 by Alois Schloegl <alois.schloegl@gmail.com>  
29 %       This function is part of the NaN-toolbox
30 %       http://pub.ist.ac.at/~schloegl/matlab/NaN/
31
32 global FLAG_NANS_OCCURED;
33
34 % check dimension
35 sz=size(x);
36
37 % find the dimension
38 if nargin==1,
39         DIM = find(size(x)>1,1);
40         if isempty(DIM), DIM=1; end;
41 end;
42
43 if DIM>length(sz),
44         sz = [sz,ones(1,DIM-length(sz))];
45 end;
46
47 D1 = prod(sz(1:DIM-1));
48 D2 = sz(DIM);
49 D3 = prod(sz(DIM+1:length(sz)));
50 D0 = [sz(1:DIM-1),1,sz(DIM+1:length(sz))];
51 y  = repmat(nan,D0);
52 q  = repmat(nan,3,1);
53 for k = 0:D1-1,
54 for l = 0:D3-1,
55         xi = k + l * D1*sz(DIM) + 1 ;
56         xo = k + l * D1 + 1;
57         t = x(xi+(0:sz(DIM)-1)*D1);
58         t = sort(t(~isnan(t)));
59         t = t(:);
60         n = length(t); 
61         if (n<D2) 
62                 FLAG_NANS_OCCURED = 1; 
63         end; 
64         
65         % q = flix(t,x);        % The following find the quartiles and median.
66                                 % INTERP1 is not an alternative since it fails for n<2;
67         x  = n*[0.25;0.50;0.75] + [0.75;0.50;0.25]; 
68         d  = x - floor(x);      % distance to next sample        
69
70         t  = t(:);
71         ix = ~logical(d);       % find integer indices
72         q(ix) = t(x(ix));       % put integer indices
73         ix = ~ix;               % find non-integer indices
74         q(ix) = t(floor(x(ix))).*(1-d(ix)) + t(ceil(x(ix))).*d(ix);  
75         
76         y(xo) = (q(1) + 2*q(2) + q(3))/4;
77 end;
78 end;
79