%% Numerical Do's and Don'ts Demo -- Balancing

%   Copyright 1986-2004 The MathWorks, Inc.
%   $Revision: 1.1.6.1 $  $Date: 2004/08/17 21:33:11 $



%% Balancing
% Mixing disparate time scales or unit scales can produce state-space
% models with coefficients that are widely spread in value. Working with 
% such poorly scaled models can lead to numerical instabilities and 
% puzzling results.



%% Poorly Scaled Model
% Below is an example of a poorly-scaled model (POORBAL).  Note the many
% orders of magnitude separating the entries of B and C, as well as the
% lower vs. upper diagonal entries in the state matrix A:
%

load numdemo            % load POORBAL model
format short g
[a,b,c,d] = ssdata(poorbal)


%%
% This model is stable with poles at:  -1.9e6, -2.6e3+7.0e4i,
% -2.6e3-7.0e4i, -4.3e3
% 

%% Pitfalls of Poor Scaling
% To illustrate the problems of poor scaling, discretize the model at 1 MHz
% (Ts = 1e-6) using the matrix-based version of C2D, and then simulate the
% step response:

clf;
ax = gca;
axis(ax,'normal')
[ad,bd] = c2d(a,b,1e-6);
step(ss(ad,bd,c,d,1e-6),1e-3);
title('Step Response of discretized POORBAL (unbalanced)')

%%
% The response diverges in spite of the continuous-time model being stable.
% The C2D conversion fails to preserve stability on this badly-scaled
% model.
%   

%% Balancing a Poorly Scaled Model
% A useful command to remedy poor scaling is SSBAL.  This command takes a
% state-space model and rescales the states to compress the range of
% numerical values in the A,B,C matrices.  This operation is called 
% "balancing":
  
wellbal = ssbal(poorbal);
[a,b,c,d] = ssdata(wellbal)

%%
% The balanced model is shown above.  Note the significantly reduced spread
% in numerical values.
%   

%% Benifits of a Balanced Model
% Next, repeat the same discretization and simulation steps with the
% balanced model (WELLBAL):

[ad,bd] = c2d(a,b,1e-6);
step(ss(ad,bd,c,d,1e-6),1e-3)
title('Step Response of discretized WELLBAL (balanced)');

%%
% The simulation now produces the expected results.
%
% Many commands in the Control System Toolbox perform balancing
% automatically.  This includes C2D when applied to a state-space model (as
% opposed to A,B matrices):

poorbal_d = c2d(poorbal,1e-6);
step(poorbal_d,1e-3)
title('Step Response of POORBAL\_D (balanced)'); 

%%
% Note that the discretized model is now stable thanks to the balancing
% performed by C2D behind the scenes.


%% Moral
% *Moral:*  Avoid working with poorly scaled models and use SSBAL to correct
% scaling problems.