Useful stuff
pole
zero
pzmap
damp
impulse
step
initial
lsim
bode
margin

% CONTINUOUS TIME

% Set up a matlab system
A = [ 0 1
0 0]
B = [ 0
1 ]
C = [ 1 0 ]
D = [ 0 ]
s1 = ss(A,B,C,D) 
impulse(s1,10)
step(s1,10)
pzmap(s1)
% Add a spring.
A = [ 0 1
-100 0]
s1 = ss(A,B,C,D) 
impulse(s1,10)
step(s1,10)
pzmap(s1)
% Add damping
A = [ 0 1
-100 -1 ]
s1 = ss(A,B,C,D) 
impulse(s1,10)
step(s1,10)
pzmap(s1)
% Very underdamped
A = [ 0 1
-100 -0.1 ]
s1 = ss(A,B,C,D) 
impulse(s1,100)
step(s1,100)
pzmap(s1)
% Close to critical damping
A = [ 0 1
-100 -20 ]
s1 = ss(A,B,C,D) 
impulse(s1,10)
step(s1,10)
pzmap(s1)
% Overdamped
A = [ 0 1
-100 -40 ]
s1 = ss(A,B,C,D) 
impulse(s1,100)
step(s1,100)
pzmap(s1)

% What does lqr say?
A = [ 0 1
0 0]
Q = [ 1 0 
0 1 ]
R = [ 1 ]
[K,S,E] = lqr(A,B,Q,R)
s2 = ss(A-B*K,B,C,D)
pole(s2)
pzmap(s2)

% What does rlocus say?
A = [ 0 1
0 -20]
s1 = ss(A,B,C,D) 
rlocus(s1)

bode(s1)

%DISCRETE TIME

% Set up a matlab system
T = 0.01
A = [ 1 T
0 1]
B = [ T*T/2
T ]
C = [ 1 0 ]
D = [ 0 ]
s1 = ss(A,B,C,D,T) 
impulse(s1,10)
step(s1,10)
% Add a spring. Note integration problem.
A = [ 1 T
-1 1 ]
s1 = ss(A,B,C,D,T) 
impulse(s1,10)
step(s1,10)
% Add damping
A = [ 1 T
-1 0.9 ]
s1 = ss(A,B,C,D,T) 
impulse(s1,10)
step(s1,10)
% Very underdamped
A = [ 1 T
-1 0.98 ]
s1 = ss(A,B,C,D,T) 
impulse(s1,10)
step(s1,10)
% Close to critical damping
A = [ 1 T
-1 0.81 ]
s1 = ss(A,B,C,D,T) 
impulse(s1,10)
step(s1,10)
% Overdamped
A = [ 1 T
-1 0.1 ]
s1 = ss(A,B,C,D,T) 
impulse(s1,10)
step(s1,10)

% Play with sisotool and rlocus
A = [ 1 T
0 0.8 ]
s1 = ss(A,B,C,D,T)
sisotool(s1)
rlocus(s1)

% What does dlqr say?
Q = [ 1 0 
0 1 ]
R = [ 1 ]
[k,s,e] = dlqr(A,B,Q,R)

s2 = ss(A-B*k,B,C,D,T)
pole(s2)
rlocus(s2)

% CONTINUOUS TIME
% UNMODELLED DYNAMICS
% Let's say we have a system with mass M=2 which we can apply a force to.
A = [ 0 1
0 0]
B = [ 0
1 ]
C = [ 1 0 ]
D = [ 0 ]
s1 = ss(A,B,C,D) 
impulse(s1,10)
step(s1,10)
pzmap(s1)

K = 10
B = 0.0001
A2 = [ 0 1 0 0 
0 0 K B
0 0 0 1
0 0 -2*K -2*B ]
B2 = [ 0
1
0
-1 ]
C2 = [ 1 0 0 0 ]
D2 = [ 0 ]
s2 = ss(A2,B2,C2,D2) 
rlocus(s2)

KK = [ 1 1 0 0 ]
s3 = ss(A2-B2*KK,B2,C2,D2)
pole(s3)

% What does dlqr say?
Q2 = [ 1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1 ]
R2 = [ 1 ]
[K,S,E] = dlqr(A2,B2,Q2,R2)

