DETRENDMA Removes a trend from data using a moving average of size 2*L+1. If 2*L+1 > length(x) then the mean is removed CALL: [y, trend] = detrendma(x,L) y = x - trend trend = moving average which is removed x = vector of data or matrix of column vectors of data L = determines the size of the moving average window Example: x = linspace(0,1,200)'; y = exp(x)+cos(5*2*pi*x)+1e-1*randn(size(x)); [y0, tr] = detrendma(y,20); plot(x,y,x,y0,'r',x,exp(x),'k',x,tr,'m') See also Reconstruct
Estimates the directional wave spectrum from timeseries | |
Estimate one-sided spectral density from data. | |
reconstruct the spurious/missing points of timeseries | |
setup all global variables of the WAFODEMO |
001 function [y, trend] = detrendma(x,L) 002 %DETRENDMA Removes a trend from data using a moving average 003 % of size 2*L+1. If 2*L+1 > length(x) then the mean is removed 004 % 005 % CALL: [y, trend] = detrendma(x,L) 006 % 007 % y = x - trend 008 % trend = moving average which is removed 009 % x = vector of data or matrix of column vectors of data 010 % L = determines the size of the moving average window 011 % 012 % Example: 013 % x = linspace(0,1,200)'; 014 % y = exp(x)+cos(5*2*pi*x)+1e-1*randn(size(x)); 015 % [y0, tr] = detrendma(y,20); 016 % plot(x,y,x,y0,'r',x,exp(x),'k',x,tr,'m') 017 % 018 % See also Reconstruct 019 020 % tested on : matlab 5.3 021 % revised pab 01.08.2001 022 % -added ; + nargchk + example + check on L 023 % - fixed a bug: y was always a column vector even if x was a row vector 024 % revised pab 13.01.2000 025 % - made trend the same size as y 026 % By Per A. Brodtkorb 21.04.1999 027 028 error(nargchk(2,2,nargin)) 029 if L<=0,error('L must be positive'),end 030 if L~=round(L), error('L must be an integer'),end 031 032 [r, c]=size(x); 033 if r==1, 034 x=x(:);%make sure it is a column 035 end 036 037 [n, m]=size(x); 038 if n<2*L+1,% only able to remove the mean 039 trend=mean(x); 040 if m==1, 041 y=x-trend; 042 else 043 y=x-trend(ones(n,1),:); 044 end 045 return 046 end 047 048 mn = mean(x(1:2*L+1,:)); 049 y = zeros(n,m); 050 y(1:L,:)=x(1:L,:)-mn(ones(L,1),:); 051 052 if 1,%new call which is much faster 053 ix = (L+1):(n-L); 054 trend = cumsum([mn;(x(ix+L,:)-x(ix-L,:))/(2*L+1)],1); 055 y(ix,:) = x(ix,:)-trend(2:end,:); 056 else % old call slow 057 trend=zeros(n-2*L,m); 058 trend(1,:)=mn; 059 for ix=L+1:n-L, 060 mn=mn+ (x(ix+L,:)-x(ix-L,:))/(2*L+1); 061 y(ix,:)=x(ix,:)-mn; 062 trend(ix-L,:)=mn; 063 end 064 end 065 mn2=trend(end,:); 066 067 if nargout>1 068 trend=[mn(ones(L-1,1),:);trend;mn2(ones(L,1),:)]; 069 if r==1, trend = trend.'; end 070 end 071 072 y(n-L+1:n,:)=x(n-L+1:n,:)-mn2(ones(L,1),:); 073 074 if r==1, y = y.'; end 075
Comments or corrections to the WAFO group