% =========================================================================
% This script assumes that a LTI model named 'Model_sys' exists in the work 
% space. Such a model can for instance be obtained with the Control and 
% Estimation Tools Manager in Simulink.
%
% Helge Smedsrud
% IKP, NTNU
% 2008
% =========================================================================

clc
close all

% Changing from state-space to transfer function form
[num,den] = ss2tf(Model_sys.a,Model_sys.b,Model_sys.c,Model_sys.d,1);

% Writing in zero-pole-gain format
G = zpk(Model_sys);

% Locating zeros
A = roots(num);

% Locating poles
B = roots(den);

% Checking stability
if ones(length(real(A)),1)'*real(A) < 0 && ones(length(real(B)),1)'*real(B) < 0
    disp('The system is stable.')
    disp(' ')
elseif ones(length(real(B)),1)'*real(B) >= 0
    disp('The system may have instability issues. Check the pole matrix B.')
    disp(' ')
end

% Steady-state gain
K = num(end)/den(end)

% Time constants
T = 1./-A;
tau = 1./-B;

% Plot a step in Model_sys
step(Model_sys)
[y,t] = step(Model_sys);

% Defining s a variable
s = tf('s');

% Comparing with a first order approximation
hold
yy = y/K;
diff = abs(yy-0.632);
u = find(diff == min(diff));
tau1 = t(u)
g = K/(tau1*s+1)
step(g)
legend('Original step response','First order approximation with \tau\rm_1 = \tau.')