% copyright Thomas Mc Avoy 1998
% Routine to scale the variables in the Tennessee Eastman problem.
% Flows flows are scaled by twice their steady state value. 
% Pressures are scaled by 600 kPa, reactor level by 50%, other levels by 50%/hr
% temperatures by 50 deg C, except reactor temp 25 deg C.  Compositions are scaled by twice ss values. 
% Compressor work is scaled by twice 
% its steady state value. Manipulated variables are scaled by twice
% their steady state value if it is less than 50%, and 
% by 100% minus their steady state value if it is greater than 50%.
% The scaled matrix is returned as k.

function [k]=scale(K,u,zs)
%load steady
%disp('MAKE SURE THAT BEFORE CALLING SCALE THE MAT FILE STEADY IS LOADED')

if nargin ~=3
	disp('YOU NEED TO INPUT THE GAIN MATRIX AND u and zs')
	error
end

[jes1,jes2]=size(K);
k=zeros(jes1,jes2);
xmeas=zs;

% Unscale
K(:,1:12)=K(:,1:12)./[ones(41,1)*u'];
K=K.*[zs*ones(1,12)];

% First scale rows. Scale factors are below.

rscale(1:6)=xmeas(1:6)*2;
rscale(7:11)=[600;50;25;xmeas(10)*2;50];
rscale(12:17)=[50;600;xmeas(14)*2;50;600;xmeas(17)*2];
rscale(18:22)=[50;xmeas(19)*2;2*xmeas(20);50;50];
rscale(23:41)=[2*xmeas(23:41)]';
k=K./(rscale'*ones(1,12));
m=1;
for i=1:12
		if u(i)<50
			cscale(m)=u(i)*2;
		else
			cscale(m)=2*(100-u(i));
		end
		m=m+1;
end

k=k.*(ones(41,1)*cscale);


 
