function zd=dtrend(z,o,brp)
%DTREND Removes trends from data sets.
%	ZD = DTREND(Z)    or   ZD = DTREND(Z,O,BREAKPOINTS)
%
%	Z is the data set to be detrended, organized with the data records as
%	column vectors. ZD is returned as the detrended data.
%	
%	If O = 0 (the default case) the sample means are removed from each of
%	the columns.
%
%	If O = 1, linear trends are removed. A continuous, piecewise linear
%	trend is adjusted to each of the data records, and then removed. The
%	interior breakpoints for the linear trend segments are contained in
%	the row vector BREAKPOINTS. The default value is that there are no
%	interior breakpoints, so that one single straight line is removed from
%	each of the data records.
%	See also IDFILT.

%	L. Ljung 7-8-87
%	Copyright (c) 1986-95 The MathWorks, Inc.
%	$Revision: 1.5 $  $Date: 1995/05/16 09:01:05 $
if nargin < 1
   disp('Usage: ZD = DTREND(Z);')
   disp('       ZD = DTREND(Z,ORDER,BREAKPOINTS);')
   return
end

[N,nz]=size(z);
if nargin<3,brp=[];end
if nargin<2,o=0;end
if o==1
   lb=length(brp);if lb==0,brp=1;lb=1;else
   if length(find(brp==1))==0,
   brp(2:lb+1)=brp;brp(1)=1;end,end
   lb=length(brp);if brp(lb)>=N,lb=lb-1;end
   for k=1:nz
    phi=zeros(lb+1,N);
    phi(1,:)=ones(1,N);
    for kb=1:lb
    int=[brp(kb):N];
    phi(kb+1,int)=10*(int-int(1))/N;
    end
    zd(:,k)=z(:,k)-phi'*(phi'\z(:,k));
    end
end
if o==0
	for k=1:nz
	zd(:,k)=z(:,k)-mean(z(:,k));
	end
end
