function [Y,p]=detrend2(X) %DETREND2 Remove linear trends from the columns of a matrix % DETREND2(X) removes the linear trend from each column of the matrix % X. % % [Y,Z]=DETREND2(X) returns the linearly detrended matrix in Y % and the slopes of the trends of the columns of the matrix X in Z. [M,N]=size(X); % Compute linear trend for each variable t=(1:M)'; t=t-mean(t); for i=1:N [P,S]=polyfit(t,X(:,i),1); p(i)=P(1); end % Remove the linear trends Y=X-t*p; if nargout==1,p=[];,end