function [y,ax,bx]=scaledata(x,x_scale)
%
%  Scales the components of the given matrix x into the given interval
%  [ x_scale(1) x_scale(2) ].
%  
%  Attention: 
%    - it is assumed that each row of the matrix corresponds to
%      a specific variable and each columns to a specific observation.
%    - if some variable has constant value according to the observations
%      its value will be scaled to the middle of the interval
% 
%  Input
%    x         matrix to be scaled
%    x_scale   interval
%
%  Output
%    y         scaled matrix
%    ax        information about the scaling;
%    bx        required for inverse transformation
%

if (x_scale(2) - x_scale(1)) <= 1.e-13
   disp('scaledata: b <= a for requested scaling interval [a,b]. Returning...')
   ax = zeros(size(x,1));
   bx = zeros(size(ax));
   return
end

a   = min(x')';
b   = max(x')';
bma = b - a;

ind = find(bma <= 1.e-13);
bma(ind) = x_scale(2) - x_scale(1);
 
ax  = (x_scale(2) - x_scale(1))./bma;
bx  = x_scale(1) - ax.*a;
bx(ind) = (x_scale(1)+x_scale(2))/2 - a(ind);

y = diag(ax)*x + repmat(bx,1,size(x,2));
