function [in,out]=build_regressors(m,z,subset);
%BUILD_REGRESSORS build the regresors for a MIMO system
%    
%    For z=[y u];
%    in{o}(t)=[y{1}(t-1),y{1}(t-2),...,y{1}(t-ny(o,1)),y{2}(t-
%    1),y{2}(t-2),...,y{2}(t-ny(o,2)), ...
%    u{1}(t-nd(O,1)),u{1}(t-1-nd(O,1)),...,u{1}(t-nu(o,1)-nd(O
%    ,1)), ...] out{o}(t)=y{o}(t) It works even if y{1} ...
%    are all vectors (useful for the computation of the
%    derivatives)
%    
%    [IN,OUT]=BUILD_REGRESSORS(M,Z,SUBSET); given the inputs
%    outputs Z=[outputs inputs], computes SUBSET regressors.
%    
%    

%MAN_PAGE_BEGIN
%
%   @purpose build the regresors for a MIMO system.
%
% For z=[y u];
%
% in{o}(t)=[y{1}(t-1),y{1}(t-2),...,y{1}(t-ny(o,1)),y{2}(t-1),y{2}(t-2),...,y{2}(t-ny(o,2)), ...
%			u{1}(t-nd(O,1)),u{1}(t-1-nd(O,1)),...,u{1}(t-nu(o,1)-nd(O,1)), ...]
% out{o}(t)=y{o}(t)
%
% It works even if y{1} ... are all vectors (useful for the computation of the derivatives)
%
%   @synopsis   [in,out]=build_regressors(m,z,subset);
%   @description  given the inputs outputs <CODE>z</CODE>=[outputs inputs],
%	computes <CODE>subset</CODE> regressors.
%
%MAN_PAGE_END

%   Copyright (c) 1998 by Antoine Duchateau			
%	$Revision: 0.1$  $Date: 11/09/98 15:48
%
%	All rights reserved


dyn=get(m,'dynamics');  

ny=dyn.ny;
nu=dyn.nu;
nd=dyn.nd;
[m,n,o]=size(z);
n_out=size(ny,1);
n_in=size(nu,2);
	
for i=1:n_out,
	start_point=max(max(ny(i,:)+(ny(i,:)>0)),max(nu(i,:)+nd(i,:)));
	if nargin>2,
		start_point=max(start_point,size(z,1)-subset+1);
	end
	
	out{i}=squeeze(z(start_point:end,i,:));
	
	in{i}=[];
	
	for j=1:n_out,
		for k=1:ny(i,j),
			in{i}=[in{i} squeeze(z(start_point-k:end-k,j,:))];
		end
	end
	
	for j=1:n_in,
		for k=1:nu(i,j),
			in{i}=[in{i} squeeze(z(start_point-k-nd(i,j)+1:end-k-nd(i,j)+1,j+n_out,:))];
		end
	end
end


