%% Numerical Do's and Don'ts Demo -- Model Type Conversions

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

%% Model Type Conversions
% You can convert any LTI model to transfer function, zero-pole-gain, or
% state-space form using the commands TF, ZPK, and SS, respectively. For
% example, given a two-input, two-output random state-space model HSS1
% created with the command
HSS1 = rss(3,2,2);

%%
% you can obtain its transfer function with the command

HTF = tf(HSS1);

%%
% For any LTI model 'sys'
% 
% * tf(sys)   % converts to transfer function
% * zpk(sys)  % converts to zero-pole-gain form
% * ss(sys)   % converts to state-space form
%

%% Issues with Conversions
% Beware that conversions are neither cheap nor free of roundoff errors,
% and can increase the model order.  You should therefore avoid converting
% back and forth between model types, especially when dealing with MIMO
% models.  As a simple illustration, convert the 2x2 state-space model HSS1
% to transfer function form, then back to state-space form, and then 
% compare the pole/zero maps for the initial and final models:

HTF = tf(HSS1);
HSS2 = ss(HTF);


subplot(211)
pzmap(HSS1,'b')
title('Pole/zero maps of HSS1 (blue)');
subplot(212)
pzmap(HSS2,'r')
title('Pole/zero maps of HSS2 (red)');


%%
% The resulting model HSS2 has twice the order of HSS1, as confirmed by 

[size(HSS1,'order') , size(HSS2,'order')]

%%
% This happens because 6 is the generic order of 2x2 transfer matrices with
% denominator of degree 3.  The reduced order 3 is an "anomaly" due to
% exact pole/zero cancellations (look for x's inside o's in the pole/zero
% map).

%% Minimal Realizations
% You can use the command MINREAL to eliminate cancelling pole/zero pairs
% and recover a 3rd-order, minimal state-space model from HSS2:

HSS2_min = minreal(HSS2);

%%
subplot(211)
pzmap(HSS1,'b')
title('Pole/zero maps of HSS1 (blue)')
subplot(212)
pzmap(HSS2_min,'r')
title('Pole/zero maps of HSS2\_min (red)')

%%
% Since extracting minimal realizations is numerically challenging, it is
% best to avoid creating nonminimal models in the first place.  (see also
% the "Model Interconnections" topic).

%% Moral
% *Moral:*   Don't abuse conversions, and stick with the state-space form for
% all computations.

