]> Creatis software - CreaPhase.git/blob - octave_packages/m/signal/detrend.m
update packages
[CreaPhase.git] / octave_packages / m / signal / detrend.m
1 ## Copyright (C) 1995-2012 Kurt Hornik
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 3 of the License, or (at
8 ## your option) 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, see
17 ## <http://www.gnu.org/licenses/>.
18
19 ## -*- texinfo -*-
20 ## @deftypefn {Function File} {} detrend (@var{x}, @var{p})
21 ## If @var{x} is a vector, @code{detrend (@var{x}, @var{p})} removes the
22 ## best fit of a polynomial of order @var{p} from the data @var{x}.
23 ##
24 ## If @var{x} is a matrix, @code{detrend (@var{x}, @var{p})} does the same
25 ## for each column in @var{x}.
26 ##
27 ## The second argument is optional.  If it is not specified, a value of 1
28 ## is assumed.  This corresponds to removing a linear trend.
29 ##
30 ## The order of the polynomial can also be given as a string, in which case
31 ## @var{p} must be either @t{"constant"} (corresponds to @code{@var{p}=0}) or
32 ## @t{"linear"} (corresponds to @code{@var{p}=1}).
33 ## @seealso{polyfit}
34 ## @end deftypefn
35
36 ## Author: KH <Kurt.Hornik@wu-wien.ac.at>
37 ## Created: 11 October 1994
38 ## Adapted-By: jwe
39
40 function y = detrend (x, p = 1)
41   ## Check input
42   if (nargin > 0 && isreal (x) && ndims (x) <= 2)
43     ## Check p
44     if (ischar (p) && strcmpi (p, "constant"))
45       p = 0;
46     elseif (ischar (p) && strcmpi (p, "linear"))
47       p = 1;
48     elseif (!isscalar (p) || p < 0 || p != fix (p))
49       error ("detrend: second input argument must be 'constant', 'linear' or a positive integer");
50     endif
51   else
52     error ("detrend: first input argument must be a real vector or matrix");
53   endif
54
55   [m, n] = size (x);
56   if (m == 1)
57     x = x';
58   endif
59
60   r = rows (x);
61   b = ((1 : r)' * ones (1, p + 1)) .^ (ones (r, 1) * (0 : p));
62   y = x - b * (b \ x);
63
64   if (m == 1)
65     y = y';
66   endif
67
68 endfunction
69
70 %!test
71 %! N=32;
72 %! x = (0:1:N-1)/N + 2;
73 %! y = detrend(x);
74 %! assert(all (all (abs (y) < 20*eps)));
75
76 %!test
77 %! N=32;
78 %! t = (0:1:N-1)/N;
79 %! x = t .* t + 2;
80 %! y = detrend(x,2);
81 %! assert(all (all (abs (y) < 30*eps)));
82
83 %!test
84 %! N=32;
85 %! t = (0:1:N-1)/N;
86 %! x = [t;4*t-3]';
87 %! y = detrend(x);
88 %! assert(all (all (abs (y) < 20*eps)));
89