%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% file uebung_control1_e.m
%
% Exercise to lesson MATLAB Simulink - Control System TB I
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

echo on;
format compact;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Creation of LTI-models
V   = 1 ;                                   % a) TF-model
T1  = 0.01 ; 
pt1 =  tf(V,[T1 1])

Ti  = 0.1 ;                                 % b) ZPK-model
int = zpk([],0,1/Ti)

Vr  = 2 ;                                   % c) SS-model
Tr  = 0.005 ;
reg = ss([-1/Tr],[Vr/Tr],[1],0)
% reg = tf([Vr/Tr],[1 1/Tr])                % TF-model alternatively 
                                            % d) FRD-model
% Creation of file frddaten.txt
% [resp,freq] = frdata(frd(tf(1,[1 0.07 0.1]),logspace(-2,1,20)),'v');
% frddaten = [real(resp) imag(resp) freq] ;
% save frddaten.txt -ascii frddaten
load frddaten.txt                           
resp = frddaten(:,1)+i*frddaten(:,2);
freq = frddaten(:,3);
sysfrd = frd(resp,freq);
bode(sysfrd,tf(1,[1 0.07 0.1]),'--')

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Discrete-time LTI-models
Ts   = 0.1 ;                                % a) TF-model
dpt1 = c2d(pt1,Ts)
dint = c2d(int,Ts)
dreg = c2d(reg,Ts)

dsystf   = tf([2 1 0],[1 1 2],-1)           % b) DSP-Format
dsysfilt = filt([2 1],[1 1 2],-1)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Working with LTI-model
plant   = pt1 * int                         % a) ALT: plant = series(int,pt1,1,1) 
forward = plant * reg                       % b) 
pre     = tf(1)                             % c) 
mess    = tf(1)
sys     = feedback(forward,mess,-1)*pre     % d)

step(plant,forward,sys,0:0.0005:0.3);       % e) Anzeige
legend('plant','forward','sys','Location','NorthWest')

Tm      = 0.05                              % f)
V       = 1
mess    = tf(1,[Tm 1])
sys2    = feedback(forward,mess,-1)*pre     % g)

step(sys,sys2,0:0.0005:0.3);                % h) step response
legend('sys','sys2','Location','NorthWest')

Tm      = 0.008                             % i)
mess3   = tf(1,[Tm 1])
sys3    = feedback(forward,mess3,-1)*pre     
step(sys,sys2,sys3,0:0.0005:0.3);           
legend('sys','sys2','sys3','Location','NorthWest')
