NLDetrendFSTS

From CCN Wiki
Jump to navigation Jump to search

A MATLAB function was created that subtracts the nonlinear trend, obtained from the global mean, from each of the time series vectors. In the course of doing so, the function plots the original data, the global mean, and the transformed data (with the trend removed).

NLDetrendFSTS.m

function dtM = NLDetrendFSTS(M, droprows)
%Removes non-linear trends from a cell array of matrices, M.
%Parameters:
%   M: a cell array of matrices.
%   drop: a vector of indices indicating the rows to be dropped before
%       detrending (default: empty; all rows are kept). Positive values are
%       relative to the start of each matrix and values less than 1 are
%       relative to the end of each matrix (e.g., [-1 0 1 2 3 4] drops the
%       first four rows, 1:4, and the last two rows, -1:0)
if isempty(droprows) || ~exist('droprows', 'var')
   droprows=[];
end

nmatrices=length(M);
dtM=cell(nmatrices,1);
 

figure(1);

for i=1:nmatrices
   A=M{i};
   %drop rows as requred
   A=dropRows(A,droprows);
   %get global mean waveform
   gmean=mean(A')';
   %find polynomial line of best fit to mean waveform
   polyord=6;
   t=(1:length(gmean))';
   [p,s,mu]=polyfit(t,gmean,polyord);
   f_y=polyval(p,t,[],mu);
   %subtract the line of best fit from the time series
   f_y_mat=repmat(f_y,1,size(A,2));
   dtA=A-f_y_mat;
   subplot(nmatrices,3, ((i-1)*3)+1);
   plot(A);
   subplot(nmatrices,3, ((i-1)*3)+2);
   plot(gmean);
   subplot(nmatrices,3, ((i-1)*3)+3);
   plot(dtA);
   dtM{i}=dtA;
end
%% Nested utility function dropRows(M,droprows)
   function M=dropRows(M,droprows)
       %receives matrix M and drops rows indexed by positive values in
       %droprows, and indexed from the end (e.g., M(end-1,:) for values
       %less than 1
       sz=size(M);
       keeprows=1:size(M,1); %rows to keep
       %convert negative droprows indices into end-relative values
       droprows=[droprows(droprows>0) droprows(droprows<1)+size(M,1)];
       keeprows(droprows)=[];%removes from rows to keep the set of rows to drop
       M=M(keeprows, :); %keep only the rows not flagged to be dropped
       %if M was 3D+, it will need to be reshaped
       sz(1)=size(M,1); %new number of rows in sz matrix, all other dimensions maintained as they were
       M=reshape(M, sz);
   end
end