You are on page 1of 41

AENG-556

MODERN
CONTROL TERM PROJECT

CONTROL OF BALL ON A
ROTATING BEAM

AKINO JOHNKENNEDY

TABLE OF CONTENTS
1. ABSTRACT
2. INTRODUCTION
3. PROBLEM DESCRIPTION
4. SYSTEM PARAMETERS
5. MODELING
6. EIGEN VALUES AND EIGEN VECTORS
7. MODAL ANALYSIS
8. LYAPUNOV STABILITY ANALYSIS
9. CONDITION NUMBER
10. CONTROLLABILITY AND OBSERVABILITY
11. BALL AND BEAM CONTROL THEORY
12. DYNAMIC SHAPING
13. SERVOMECHANISM FULL STATE FEEDBACK POLE PLACEMENT DESIGN
14. OBSERVER BASED COMPENSATOR DESIGN
15. CONCLUSION

APPENDIX
MATLAB CODE

Page 2

1. ABSTRACT
The ball and beam system is a very simple and powerful control system problem. The
easy construction of this system combined with its challenging control design requirement
makes it one of the most interesting models. The model contains a horizontal beam which can
pivot about one end; a servo motor whose shaft is connected to the other end of the beam; and
a ball that can freely roll on top of the beam.

2. INTRODUCTION
The ultimate goal of this project is to develop a control system for the ball and beam
control system. In this project, a ball is free to roll along the track of a beam. The control
problem involves moving the ball from one position on the track to another by controlling the
beam angle. The control job is to automatically regulate the position of the ball on the beam by
Changing the angle of the beam.
This is a difficult control task because the ball does not stay in one place on the beam but
moves with acceleration that is approximately proportional to the tilt of the beam. In control
terminology the system is open loop unstable because the system output (the ball position)
increases without limit for a fixed input (beam angle). Feedback control must be used to
stabilize the system and to keep the ball in a desired position on the beam. The control system
is simulated in Matlab where ball and beam system is modeled. Data from the Matlab is
analyzed.

Page 3

3. PROBLEM DESCRIPTION
The ball is modeled by a mass, m, a radius, r, and a mass moment of inertia, Jb. The beam is
modeled by a mass moment of inertia, J. A torque, is applied at the beam center to change the
angle of the beam to adjust the position of the ball. The major control objective is to position
the ball anywhere along the beam. This is a difficult problem because the only actuator
available is the beam itself and its rotation. Moreover, this is a nonlinear and unstable system.

The inherent dynamics of the ball and beam system are described by a set of nonlinear
differential equations. Instead of designing a single nonlinear control law, a collection of linear
controls can be designed about various trim conditions. This project focuses on the control of
the ball position about a trim condition.

Page 4

4. SYSTEM PARAMETERS
Physical parameters of the ball:
Mass of the ball, mball:

0.065 kg

Radius of the ball, rball:

0.025 m

Ball mass moment of Inertia, Jball:

(2/5)*mball*(rball)2 kg-m2

Physical parameters of the beam:


Mass of the beam, mbeam:

0.65 kg

Length of the beam, lbeam:

0.425 m

Beam mass moment of Inertia, Jbeam:

(1/12)*mbeam*(lbeam)2 kg-m2

5. MODELING:
The ball and beam system modeling involves two steps
1. Developing a nonlinear mathematical model and
2. Linearizing the non linear model
Analysis of motion of ball:

y
ax

Fx max

Fr mg sin m &
p& p&2

Jb
&
p& mg sin m &
p& p&2
2
r
Jb

p& mg sin mp&2 0


r 2 m &

Page 5

Fy ma y

& 2&p&
N mg cos m p&
& 2&p&
N mg cos m p&

M G J b
&
F r J &
r

b b

p&
&

Fr r J b
r
J
Fr 2b &
p&
r
Analysis of motion of beam (in xyz):
M A J A
&
Np J&

& 2&p& J&


&
p mg cos m p&

J mp && 2mpp&& mgp cos


2

Therefore the nonlinear model of the system is:


Jb

p& mg sin mp&2 0


r 2 m &

2
mp J && 2mpp&& mgp cos

Page 6

And its state space elements are:


T
x p p& & x1 x2 x3
u
y p

x4

Nonlinear State Space Model:


x&
1 x2 f1

x&
2 b x1 x4 g sin x3

f2 ,

m
Jb
m
r2

x&
3 x4 f 3
x&
4

2mx1 x2 x4 mgx1 cos x3 u


f4
mx12 J

y x1

Initial conditions for Steady, level beam; constant ball position


%
x%
1 p p0
% 0
x% p&
2

%
x%
3 0
&
%
x%
4 0
u% % mgx%
1

Obtaining the A, B, C, D matrices:


C 1 0 0 0
D0
Page 7

0
0
0
mg
mp0 2 J

f
( x, u )

[ x%%
,u ]

0
0
0

f
( x, u )

[ x%%
,u ]

1 0 0
0 bg 0
0 0 1

0
0 0

mp0 2 J

6. EIGEN VALUES AND EIGEN VECTORS:


The Eigen values of the system are
Eig =

[ ]
4.54
0+4.54 i
04.54 i
4.54

Page 8

Plot Of Eigen Values

Right Eigen Vector of the system is

R_Eig =

0.06880.0688i 0.0688 i0.0688


0.3131 0.3131 0.31310.3131
0.20340.2034 i 0.2034 i.2034
0.92510.9251 0.92510.9251

Left Eigen Vector of the system is

L_Eig =

0.9251 0.9251 0.92510.9251


0.2034 0.2034 i0.2034 i .2034
0.3131 0.31310.31310.3131
0.06880.0688 i0.0688i0.0688

7. MODAL ANALYSIS:
In this, the function computes the mode sensitivities for each state associated with the matrix
A. This gives an indication of which states influence each mode. This function also computes
a set of metrics for each mode. Note that frequency components of a mode exist if
eigenvectors have complex conjugate pairs.so, the mode sensitivity matrix and mode metrics
are as follows:

Page 9

Msens =
0.2500
0.2500
0.2500
0.2500

0.2500
0.2500
0.2500
0.2500

0.2500
0.2500
0.2500
0.2500

0.2500
0.2500
0.2500
0.2500

Mmetric =
1.0e+15 *
0.0000 -1.0406 -1.0406 -0.0000
-0.0000 0.0000 0.0000 -0.0000
-0.0000 -0.7532 -0.7532 -0.0000

8. LYAPUNOV STABILITY ANALYSIS:


Lyapunov stability is a very mild requirement on equilibrium points. In particular, it
does not require that trajectories starting close to the origin tend to the origin
asymptotically. Also, stability is defined at a time instant t0. Uniform stability is a
concept which guarantees that the equilibrium point is not losing stability. The
Sylvester's Method was performed to determine if P is positive definite.
For this ball and beam model, P is not positive definite. System is unstable.

Page 10

18

x 10

d1/dt v. 1 Phase Portrait

d2/dt v. 2 Phase Portrait

19

x 10

-0.2
6
-0.4

-0.6

d2/dt, rad/s ec

d1/dt, rad/s ec

-0.8
4

-1

3
-1.2

-1.4

-1.6
1
-1.8

, rad
1

10

15

-2
-5

17

x 10

-4

-3

, rad
2

-2

-1

0
18

x 10

Phase portraits to enforce stability analysis

9. CONDITION NUMBER:
The condition number is an application of the derivative, and is formally defined as the value
of the asymptotic worst-case relative change in output for a relative change in input. The
"function" is the solution of a problem and the "arguments" are the data in the problem. The
condition number is frequently applied to questions in linear algebra, in which case the
derivative is straightforward but the error could be in many different directions, and is thus
computed from the geometry of the matrix. More generally, condition numbers can be defined
for non-linear functions in several variables.
A problem with a low condition number is said to be well-conditioned, while a problem with a
high condition number is said to be ill-conditioned.
For this ball and beam system, the Conditional number is Cn = 61.1140.

10. Controllability and Observability Analysis:

Page 11

A system is said to be completely controllable if there exists an unconstrained control


u(t) that can transfer any initial state x(t0) to any other desired location x(t) in a finite
time,
to<= t <= T.
For the system
x = Ax+B u

We can determine whether the system is controllable by examining the algebraic


condition
Rank [B AB A2B An-1B] = n
The matrix A is an n X n matrix and B is an n X 1 matrix. For multi-input systems, B
can be n X m, where m is the number of inputs.

The matrix [B AB A2B An-1B] is called the controllability matrix and is represented
by the letter P and has a dimensions of n x nm

In the present ball and beam model, Rank (P) = 4 =length (A)
Therefore the system is controllable.
System Passed PBH Rank Test. System is controllable.
System Passed PBH Eigenvector Test. System is controllable.
Degree of Controllability is 0.5000

Page 12

A system is said to be completely observable if there exists a finite time T such that the initial
state x (0) can be determined from the observation history y(t) given the control u(t),
0<= t <= T.
In the present ball and beam model, Rank(Q) = 4 =length (A)
So, the system is observable.
System PASSED PBH Eigenvector Test. System is observable.
System PASSED PBH Rank Test. System is observable.
The degree of observability is 0.0688.

11. Ball & Beam Control Theory


This section will present an overview of the control strategy to be used, describe the ball
and beam model, and discuss controller design.
The ball and beam system consists of a servo motor driven beam with a ball free to roll on
the beam. Manipulating the beam angle controls the ball position. Initially the forth order
system is made to behave like a second order system by adding four additional poles to the
system. The Wn, and zeta values are calculate and are used ITAE 4th order equation. Later a
servo-controller is developed to make the system more controllable.

12. Dynamic shaping


The dynamic shaping involves selection of a set of desired eigenvalues such that the
transient response behaves similar to a 2nd order dominant response with a percent overshoot
less than 5% and a settling time less than 0.5 seconds.

Page 13

The present overshoot and settling times are used to calculate the desired W n and Zeta
for the system. These values are used to calculate the desired pole locations for given
conditions are taken from the ITAE 4th order equation.
The Table below shows the step response info the second order and desired ITAE system of
fourth order.
2nd order

Parameter
Rise time
Settling Time
Settling Min
Settling Max
Over Shoot
Under Shoot
Peak
Peak Time

0.5427
1.5515
0.9005
1.0500
5
0
1.0500
1.1225

ITAE 4th
order
0.6465
1.1678
0.9042
1.0192
1.9196
0
1.0192
1.3773

Step Response information for Desired Dominant 2nd order system and 4 th Order ITAE system
Step Response

1.4

1.2

Amplitude

0.8

0.6

0.4

0.2

0.5

1.5

2.5

3.5

Time (seconds)

Step Response for Desired Dominant 2nd order system and 4th Order ITAE system

13. SERVOMECHANISM FULL STATE FEEDBACK POLE


PLACEMENT DESIGN
Page 14

A feedback controller design procedure would need to incorporate information of the


speed of the actuators such that certain limits placed on actuator rates (i.e., magnitude
response over time) will not be exceeded. A closed loop system is built and a tracker is added
to build a servomechanism.
The Open-loop and closed loop polar of the model states are plotted.

17

16

18

Model States vs. Time

x 10

14
12

10

Pdot

8
6

3
2

0
-2

5
Time, s

-1

10

18

0.5

x 10

5
Time, s

10

5
Time, s

10

18

x 10

x 10

0
-0.5

-1
d/dt, rad/sec

, rad

-1.5
-2
-2.5

-5

-10

-3
-3.5

-15

-4
-4.5

5
Time, s

10

-20

Model states vs. time


And a step response of the closed loop tracker is shown in the figure below:

Page 15

Step response for servomechanism.

1.4
1.2

, rad
2

1
0.8
0.6
0.4
0.2
0

5
Time, sec

10

Step response for servomechanism.

A frequency analysis is performed on the Servomechanism and results are shown below:

NYQUIST PLOT:

Page 16

Nyquist

2
1.5
1

Im(L)

0.5

radius = 1.005

0
-0.5
-1
-1.5
-2
-2

-1.5

-1

-0.5

0
Re(L)

0.5

1.5

LOOP GAIN BODE MAGNITUDE:


Bode

60

50

40

Magnitude dB

30

20

10

LGCF = 107.9681

-10

-20 -1
10

10

10
Frequency (rps)

LOOP GAIN BODE PHASE:


Page 17

10

10

Bode

200

150

100

Phase deg

50

-50

-100

-150

-200 -1
10

10

10
Frequency (rps)

10

10

RETURN DIFFERENCE 1+L MAGNITUDE:


|I+L| at input

60

50

Magnitude dB

40

30

20

10

0 -1
10

min = 1.005

10

10
Frequency (rps)

10

STABILITY ROBUSTNESS 1+INV(L) MAGNITUDE:


Page 18

10

|I+inv(L)| at Plant Input

20

15

min = 0.91998

Magnitude dB

10

-5 -1
10

10

10
Frequency (rps)

10

10

SENSITIVITY:
|S| at Plant Output

40

20

Magnitude dB

0
max = 29.8899
-20

-40

-60

-80
-1
10

10

10
Frequency (rps)

COMPLEMENTARY SENSITIVITY:
Page 19

10

10

|T| at Plant Output

30

20

10

Magnitude dB

-10

max = 29.3423

-20

-30

-40

-50

-60 -1
10

10

10
Frequency (rps)

10

10

NOISE TO CONTROL MAGNITUDE:


55

Noise-to-Control Transfer Function Matrix

50

Magnitude dB

45

40

35

30

25 -1
10

10

10
Frequency (rps)

10

It is observed that the system is too sensitive to noise and disturbance.

Page 20

10

14. OBSERVER BASED COMPENSATOR DESIGN


An observer is introduced into the system using observer error eigenvalues that are a scaled set
of the state feedback eigenvalues. The Eigen values are scaled such that the observer error
dynamics are sufficiently faster that the state control without excessively large gains.
The observer error is plotted.
Model States vs. Time

P /dt obs . error

0.2
0.1
0
-0.1

obs . error, rad

5
Time, s

10
5
0
-5
-10

5
Time, s

-5

10

d/dt obs . error, rad/s ec

P obs . error

0.3

10

5
Time, s

10

5
Time, s

10

100
50
0
-50
-100

Observer error

The step response of the closed loop tracker is shown in figure.

STEP RESPONSE OF THE CLOSED LOOP TRACKER:

Page 21

Step response for servomechanism designs

1.4
1.2

, rad
2

1
0.8
State
Observer

0.6
0.4
0.2
0

5
Time, sec

A frequency analysis is performed on the observer and results are shown below:

NYQUIST PLOT:
Nyquist

2
1.5
1

Im(L)

0.5

radius = 0.38196

0
-0.5
-1
-1.5
-2
-2

-1.5

-1

-0.5

0
Re(L)

0.5

LOOP GAIN BODE MAGNITUDE:

Page 22

1.5

10

Bode

40
20
0

LGCF = 11.913

Magnitude dB

-20
-40
-60
-80
-100
-120
-140
-160 -1
10

10

10
Frequency (rps)

10

10

LOOP GAIN BODE PHASE:


Bode

200
150
100

Phase deg

50
0
-50
-100
-150
-200 -1
10

10

10
Frequency (rps)

Page 23

10

10

RETURN DIFFERENCE 1+L MAGNITUDE:


|I+L| at input

30
25

Magnitude dB

20
15
10

min = 0.38196

5
0
-5
-10 -1
10

10

10
Frequency (rps)

10

10

STABILITY ROBUSTNESS 1+INV(L) MAGNITUDE:


|I+inv(L)| at Plant Input

160
140
120

Magnitude dB

100
80
60
40
20
min = 0.40373
0
-20 -1
10

10

10
Frequency (rps)

SENSITIVITY:
Page 24

10

10

|S| at Plant Output

5
0

Magnitude dB

-5
-10

max = 1.1048

-15
-20
-25
-30 -1
10

10

10
Frequency (rps)

10

10

COMPLEMENTARY SENSITIVITY:
|T| at Plant Output

20
0
max = 1.024
-20

Magnitude dB

-40
-60
-80
-100
-120
-140
-160 -1
10

10

10
Frequency (rps)

NOISE TO CONTROL MAGNITUDE:


Page 25

10

10

70

Noise-to-Control Transfer Function Matrix

60

Magnitude dB

50
40
30
20
10
0
-10 -1
10

10

10
Frequency (rps)

10

10

15. CONCLUSION

The ball-on-beam system is useful for demonstrating the benefits of basic control methods and
for demonstrating the effect of delay in a feedback control system. It is an inexpensive
educational tool for teaching systems and controls and for showing the value of controls
education. It is also a good project for embedded control because its design and
implementation involve all the basic components of an embedded control system and is simple
enough to be constructed in one semester.

Page 26

APPENDIX
MATLAB CODE
set(0,'DefaultTextInterpreter','tex');
clear all
clc
close all
%%%%%%%%%%%%%%%%%%% STATE SPACE DESCRIPTION %%%%%%%%%%%%%%%%%%%%
A = [0 1 0 0;
0 0 -7 0;
0 0 0 1;
-61.114 0 0 0];
B = [0 0 0 95.842]';
C = [1 0 0 0];
% Get the number of states, n, number of controls, m, and the number of
% outputs, p.
[n,m] = size(B);
p = size(C,1);
D = zeros(p,m);
% Define the state space model.
sys_ss = ss(A,B,C,D);
% Convert to transfer function.
sys_tf = tf(sys_ss);
% Convert to zero-pole description.
sys_zpk = zpk(sys_ss);
% Convert back to state space
sys_ssa = ss(sys_tf);
%%%%%%%%%%%%%% SIMULATION OF STATE SPACE SYSTEM %%%%%%%%%%%%%%%
% Define simulation time parameters
dt = 0.01;
tfinal = 10;
time_s = 0:dt:tfinal;
% Zero input for all time
u = zeros(size(time_s));
% Initial conditions on states.
x0 = [0.1;0;0;0];
% Find the characteristic polynomial.
CharPoly = poly(A);
% Find the system poles.
Poles = roots(CharPoly)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Analysis%%%%%%%%%%%%%%%%%%%%%%%%%
%
[R_eig,Eig]=eig(A);
disp('Eigen Values are:')
Eigs0 = Eig
disp('Right Eigen Vector is :');

Page 27

V = R_eig
%Left Eigen Value
[L_eig,Eig]=eig(A.');
L_eig = conj(L_eig);
disp('Left Eigen Vector is :');
W = L_eig

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Modal Analysis %%%%%%%%%%%%%%%%%%%%%


disp('Modal analysis');
[Msens, Mmetric] = perform_mode_analysis(A);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Stablity Analysis %%%%%%%%%%%%%%%%%%
% Perform a stability analysis using Lyapunov stability.
disp('Lyapunov Stability Analysis.');
% Find the poles with zero real part.
i_zero_real = find(real(Poles) == 0);
if ~isempty(i_zero_real)
% Lyapunovstabilty analysis will not work if there is at least one
% pole with zero real part. At this point, we can only check for
% marginally stable or unstable systems.
else
% Lyapunov stability analysis will work.
% Form a positive definite matrix, Q.
Q = eye(n);
% Solve the Lyapunov equation for P.
P = lyap(A,Q);
% Perform Sylvester's Method to determine if P is positive definite.
pm = zeros(1,n);
fori = 1:n
pm(i) = det(P(1:i,1:i));
end
if all(pm > 0)
disp('P is positive definite. System is asymptotically stable.');
elseif any(pm < 0)
disp('P is not positive definite. System is unstable.');
else
disp('P is positive semi-definite. Try another Q.');
end
end
disp(' ');
Plot phase portraits to enforce stability analysis
[Yo,t,Xo] = lsim(sys_ss,u,time_s,x0);
figure
subplot(1,3,1);
plot(Xo(:,1),Xo(:,2));grid
xlabel('\theta_1, rad');ylabel('d\theta_1/dt, rad/sec');
title('d\theta_1/dt v. \theta_1 Phase Portrait');
subplot(1,3,2);
plot(Xo(:,3),Xo(:,4));grid
xlabel('\theta_2, rad');ylabel('d\theta_2/dt, rad/sec');
title('d\theta_2/dt v. \theta_2 Phase Portrait');
%%%%%%%%%%%%%%%%%%%%%%% CONTROLLABILITY %%%%%%%%%%%%%%%%%%%%%%%
disp(' ');
disp(' ');
%Conditional Number of the sysytem

Page 28

disp('Conditional number of the syatem is :')


% Compute the condition number for impending singularity.
Cn = cond(A)

% Compute the controllability matrix, P, using the MATLAB function.


P = ctrb(sys_ss);
% Determine if the system is controllable by checking the rank of P.
% The rank of P should match the number of rows (or columns) of the square
% matrix A.
if rank(P) == n
disp('The system is controllable.');
else
disp('The system is NOT controllable.');
end
disp(' ');
% Perform the Popov-Belevich-Hautus eigenvector test for controllability.
% Check the inner product of each left eigenvector with B.
disp('Popov-Belevich-Hautus Eigenvector Test.');
PBHe = zeros(n,1);
fori = 1:n
PBHe(i) = W(:,i)'*B;
end
if any(PBHe == 0)
disp('System FAILED PBH Eigenvector Test. System is NOT controllable');
else
disp('System PASSED PBH Eigenvector Test. System is controllable.');
end
disp(' ');
% Perform the Popov-Belevich-Hautus rank test for controllability. Check
% the rank of [sI-A B] for each eigenvector.
disp('Popov-Belevich-Hautus Rank Test.');
PBHr = zeros(n,1);
fori = 1:n
PBHr(i) = rank([Eig(i)*eye(n,n)-A B]);
end
if any(PBHr ~= n)
disp('System FAILED PBH Rank Test. System is NOT controllable');
else
disp('System PASSED PBH Rank Test. System is controllable.');
end
disp(' ');
% Degree of Controllability between Mode i and Control j.
DoC = zeros(n,m);
fori = 1:n
for j = 1:m
DoC(i,j) = abs(dot(B(:,j), W(i,:))/norm(B(:,j))/norm(W(i,:)));
end
end
disp(' ');
disp(' ');
disp('Degree of Controllablity');
% Degree of Controllability between Mode i and Control j.
DoC = zeros(n,m);
fori = 1:n
for j = 1:m
DoC(i,j) = abs(dot(B(:,j), W(i,:))/norm(B(:,j))/norm(W(i,:)));
end

Page 29

end
DoC

%%%%%%%%%%%%%% CONTROLLER CANONICAL FORMS (CCF) %%%%%%%%%%%%%%%


% Compute the inverse matrix Pccfi.
Pccfi = zeros(n,n);
base = CharPoly(n:-1:2);
fori = n:-1:1
ifi == n
% Last row. Set the first element to 1.
Pccfi(i,1) = 1;
else
% Populate the ith row
Pccfi(i,1:n-i+1) = [base(i:end) 1];
end
end
% Compute the Transformation matrix, Tccf.
Tccf = P*Pccfi;
% Compute the CCF matrices.
Accf = Tccf\A*Tccf;
Bccf = Tccf\B;
Cccf = C*Tccf;
Dccf = D;
%%%%%%%%%%%%%%%%%%%%%%% OBSERVABILITY %%%%%%%%%%%%%%%%%%%%%%%%
% Compute the observability matrix, Q, using the MATLAB function.
Q = obsv(sys_ss);
% Determine if the system is observable by checking the rank of Q.
% The rank of Q should match the number of rows (or columns) of the square
% matrix A.
if rank(Q) == n
disp('The system is observable.');
else
disp('The system is NOT observable.');
end
disp(' ');
% Verify MATLAB by using the observability formula. Initialize this
% matrix to the size of n*p x n, where p is the number of rows of C.
p = size(C,1);
Q1 = zeros(n*p,n);
fori = 1:n
ifi == 1
% Insert the first row.
Q1(p*(i-1)+1:p*i,:) = C;
else
% Multiply the previously stored p rows by A, and store it.
Q1(p*(i-1)+1:p*i,:) = Q1(p*(i-2)+1:p*(i-1),:)*A;
end
end
% Perform the Popov-Belevich-Hautus eigenvector test for controllability.
% Check the inner product of each left eigenvector with B.
disp('Popov-Belevich-Hautus Eigenvector Test.');
PBHoe = zeros(p,n);
fori = 1:n
PBHoe(:,i) = C*V(:,i);
end
if any(abs(sum(PBHoe,1)) <= 1e-9)
disp('System FAILED PBH Eigenvector Test. System is NOT observable');
else
disp('System PASSED PBH Eigenvector Test. System is observable.');
end

Page 30

disp(' ');
% Perform the Popov-Belevich-Hautus rank test for controllability. Check
% the rank of [sI-A B] for each eigenvector.
disp('Popov-Belevich-Hautus Rank Test.');
PBHor = zeros(n,1);
fori = 1:n
PBHor(i) = rank([C; Eigs0(i)*eye(n,n)-A]);
end
if any(PBHor ~= n)
disp('System FAILED PBH Rank Test. System is NOT observable.');
else
disp('System PASSED PBH Rank Test. System is observable.');
end
disp(' ');
% Degree of Observability between Mode i and Measurement j.
DoO = zeros(p,n);
for j = 1:p
fori = 1:n
DoO(j,i) = abs(dot(C(j,:), V(:,i))/norm(C(j,:))/norm(V(:,i)));
end
end
disp('Degree of Observablity');
DoO
%%%%%%%%%%%%%%% OBSERVER CANONICAL FORMS (OCF) %%%%%%%%%%%%%%%%
% Compute the OCF form of the observability matrix.
Qocf = inv(Pccfi);
% Compute the Transformation matrix, Tocf = inv(Q)Qocf.
Tocf = Q\Qocf;
% Compute the CCF matrices.
Aocf = Tocf\A*Tocf;
Bocf = Tocf\B;
Cocf = C*Tocf;
Docf = D;

%%%%%%%%%%%%%%%%%%%%%%% DYNAMIC SHAPING %%%%%%%%%%%%%%%%%%%%%%%


% Determine a desired response for the system. Two approaches are
% investigated: (1.) second order dominant; (2.) 6th order ITAE.
% Specify the overshoot percentage and settling time.
PO = 5;
ts = 1.5;
tr = 0.25;
% Determine damping ratio from PO and natural frequency from settling time
% and zeta.
term = pi^2 + log(PO/100)^2;
zeta = abs(log(PO/100))/sqrt(term);
wn = 4/(zeta*ts);
% Desired 2nd order system.
num2 = wn^2;
den2 = [1 2*zeta*wn wn^2];
Des2 = tf(num2,den2);
% Dominant 2nd order eigenvalues.
DesEig2 = roots(den2);
%%%%% APPROACH #2 : 4th ORDER ITAE %%%%%
% 4th Order ITAE system.
num4 = wn^4;
den4 = [1 2.1*wn 3.4*wn^2 2.7*wn^3 1*wn^4 ];
Des4 = tf(num4,den4);

Page 31

% 4th Order Desired eigenvalues.


DesEig4 = roots(den4);
% Step response of systems.
figure
step(Des2,Des4);grid
disp('Step Response info for Desired Dominant 2nd order system');
stepinfo(Des2)
disp('Step Response info for Desired 6th Order ITAE system');
stepinfo(Des4)
%%%%%%%%%%%%%%%%%%%%%%% CHAPTER 7 : CONTROL DESIGN %%%%%%%%%%%%%%%%%%%%%%%%
% Designs two controllers. The first is a state feedback to regulate the
% initial state x0 to the origin. The second is to design a servo
% mechanism reference tracker.
% Compute the state f'eedback regulator based upon the 6th order ITAE
% eigenvalues.
K = place(A,B,DesEig4);
% Construct the closed loop state space description.
% Ac = A-B*K;
% Bc = B;
% Cc = C;
% Dc = D;
% Form plant system. Set output matrix for state feedback control.
sys_p.Ap = A;
sys_p.Bp = B;
sys_p.Cp = eye(n);
sys_p.Dp = zeros(n,1);
% Form controller system.
sys_c.Ac = 0;
sys_c.Bc1= 0;
sys_c.Bc2= 0;
sys_c.Cc = 0;
sys_c.Dc1= -K;
sys_c.Dc2= 0;
% Form closed loop system.
[Ac,Bc,Cc,Dc] = closed_loop_system(sys_p, sys_c);
sys_cl = ss(Ac,Bc,Cc,Dc);
% Closed-loop response (zero input, ICs).
[Yc,t,Xc] = lsim(sys_cl,u,time_s,x0);
% Open-loop and closed loop plors of the model states.
figure
subplot(2,2,1);
plot(t,Xo(:,1),'r--',t,Yc(:,1),'b-');grid on
xlabel('Time, s');
ylabel('P');
title('Model States vs. Time')
subplot(2,2,2);
plot(t,Xo(:,2),'r--',t,Yc(:,2),'b-');grid on
xlabel('Time, s');
ylabel('P_dot');
subplot(2,2,3);
plot(t,Xo(:,3),'r--',t,Yc(:,3),'b-');grid on
xlabel('Time, s');
ylabel('\theta, rad');
subplot(2,2,4);
plot(t,Xo(:,4),'r--',t,Yc(:,4),'b-');grid on
xlabel('Time, s');
ylabel('d\theta/dt, rad/sec');

Page 32

% Modify the controllable pair (Asv,Bsv) for a servo-mechanism tracker.


nrA = size(A,1);
nrC = size(C,1);
ncB = size(B,2);
nr =nrA + nrC;
Asv = zeros(nr,nr);
Asv(1:nrA,1:nrA) = A;
Asv(nrA+1:nr,1:nrA) = -C;
Bsv = zeros(nrA+nrC,ncB);
Bsv(1:nrA,1:ncB) = B;
% Add an additional desired pole for the tracker integrator.
DesEigsv = [DesEig4;-100];
% Compute the tracker gains.
Ksv = place(Asv,Bsv,DesEigsv);
% % Construct the closed loop state space description.
% Kv = Ksv(1:nrA);
% kI= -Ksv(end);
% Aclsv = [A-B*Kv, B*kI;-C, zeros(nrC,ncB)];
% Bclsv = [zeros(nrA,1);1];
% Cclsv = [C, 0];
% Dclsv = 0;
% Form plant system. Set output matrix for state feedback control.
sys_p.Ap = A;
sys_p.Bp = B;
sys_p.Cp = eye(nrA);
sys_p.Dp = zeros(nrA,1);
% Form controller system.Tracking on Theta2 state.
kI = -Ksv(end);
Kv = Ksv(1:nrA);
sys_c.Ac = 0;
sys_c.Bc1= -C;
sys_c.Bc2= 1;
sys_c.Cc = kI;
sys_c.Dc1= -Kv;
sys_c.Dc2= 0;
% Form closed loop system.
[Aclsv, Bclsv, Cclsv, Dclsv] = closed_loop_system(sys_p, sys_c);
sys_clsv = ss(Aclsv,Bclsv,Cclsv,Dclsv);
% Perform a step response of the closed loop tracker.
[Y_clsv, t_clsv] = step(sys_clsv,tfinal);
figure
plot(t_clsv, Y_clsv(:,1));grid on
xlabel('Time, sec');
ylabel('\theta_2, rad');
title('Step response for servomechanism.');
%%%%% FREQUENCY ANALYSIS %%%%%
% Perform frequency analysis of servo tracker.
w = logspace(-1,3,400);
freq_resp = freq_analysis(sys_p, sys_c, w, 1, 3);
% Plot frequency data.
plot_freq_resp(freq_resp, w);
%%%%%%%%%%%%%%%% OBSERVERS FOR STATE FEEDBACK %%%%%%%%%%%%%%%%%
% Design observer for regulation of state dynamics via full state observer
% feedback.
% Choose desired observer eigenvalues as X times control law eigenvalues.
ObsEig4 = 6*DesEig4;
% Compute the observer error gain matrix, L.
L = place(A', C', ObsEig4)';

Page 33

% Build closed loop system with observer error dynamics.


Ar = [(A-B*K) B*K; zeros(size(A)) (A-L*C)];
Br = [B; zeros(size(B))];
Cr = [C zeros(size(C))];
Dr = D;
JbkRr = ss(Ar, Br, Cr, Dr);
% Define some initial conditions for the observer. Give some diversity
% from the initial conditions on the state.
xr0 = [0.15;0.1;0.1;0.0010];
% Regulation.
r = zeros(size(time_s));
[Yr, t, Xr] = lsim(JbkRr, r, t, [x0;xr0]);
% Plot the open-loop, closed-loop state feedback and closed-loop
figure
plot(t,Yo,'r--', t, Yc(:,3), 'b--', t, Yr, 'g-.');grid;
xlabel('Time, sec');
ylabel('\theta_2, rad');
legend('Open-loop', 'Closed-loop', 'w/ Observer','Location','Best');
% Plot the observer error.
figure
subplot(2,2,1);
plot(t,Xr(:,5),'b-');grid on
xlabel('Time, s');
ylabel('P obs. error');
title('Model States vs. Time')
subplot(2,2,2);
plot(t,Xr(:,6),'b-');grid on
xlabel('Time, s');
ylabel('P/dt obs. error');
subplot(2,2,3);
plot(t,Xr(:,7),'b-');grid on
xlabel('Time, s');
ylabel('\theta obs. error, rad');
subplot(2,2,4);
plot(t,Xr(:,8),'b-');grid on
xlabel('Time, s');
ylabel('d\theta/dt obs. error, rad/sec');
% subplot(3,2,5);
% plot(t,Xr(:,11),'b-');grid on
% xlabel('Time, s');
% ylabel('x obs. error, m');
% subplot(3,2,6);
% plot(t,Xr(:,12),'b-');grid on
% xlabel('Time, s');
% ylabel('dx/dt obs. error, m/sec');
% Construct the observer-based closed loop servo system.
% Aosv = [A B*kI -B*Kv; ...
%
-C zeros(1,size(Asv,1)); ...
%
L*C B*kI A-B*Kv-L*C];
% Bosv = [zeros(size(A,1),1); 1; zeros(size(A,1),1)];
% Cosv = [C zeros(1,size(Asv,1))];
% Form plant system. Set output matrix for just theta2.
sys_p.Ap = A;
sys_p.Bp = B;
sys_p.Cp = C;
sys_p.Dp = 0;
% Form controller system.Tracking on Theta2 state.
sys_c.Ac = [zeros(1,size(B*kI,2)), zeros(1,size(A-B*Kv-L*C,2)); ...
B*kI, A-B*Kv-L*C];
sys_c.Bc2 = [1;zeros(nrA,1)];
sys_c.Bc1 = [-1;L];
sys_c.Cc = [kI -Kv];

Page 34

sys_c.Dc1 = zeros(ncB,nrC);
sys_c.Dc2 = zeros(ncB,ncB);
% Construct Closed Loop system.
[Aosv, Bosv, Cosv, Dosv] = closed_loop_system(sys_p, sys_c);
sys_oclsv = ss(Aosv, Bosv, Cosv, Dosv);
% Perform a step response of the closed loop tracker.
r = ones(size(time_s));
[Y_oclsv, t_oclsv, X_oclsv] = lsim(sys_oclsv, r, t, [zeros(5,1);xr0]);
figure
plot(t_clsv, Y_clsv(:,1),'b-',t_oclsv, Y_oclsv,'r--');grid on
xlabel('Time, sec');
ylabel('\theta_2, rad');
title('Step response for servomechanism designs');
legend('State', 'Observer', 'Location', 'Best');
%%%%% FREQUENCY ANALYSIS %%%%%
% Perform frequency analysis of servo tracker.
w = logspace(-1,3,400);
freq_resp = freq_analysis(sys_p, sys_c, w, 1, 1);
% Plot frequency data.
plot_freq_resp(freq_resp, w);

CLOSED LOOP SYSTEM:


function [A,B,C,D] = closed_loop_system(sys_p, sys_c)
% Extract plant matrices.
Ap = sys_p.Ap;
Bp = sys_p.Bp;
Cp = sys_p.Cp;
Dp = sys_p.Dp;
% Extract controller matrices.
Ac = sys_c.Ac;
Bc1 = sys_c.Bc1;
Bc2 = sys_c.Bc2;
Cc = sys_c.Cc;
Dc1 = sys_c.Dc1;
Dc2 = sys_c.Dc2;
% Intermediate matrices.
Dc1Dp = Dc1*Dp;
Z = eye(size(Dc1Dp,1)) - Dc1Dp;
DpiZDc1 = Dp*inv(Z)*Dc1;
if (all(abs(sys_c.Ac(:)) < 1e-6) && all(abs(sys_c.Bc1(:)) < 1e-6) && ...
all(abs(sys_c.Bc2(:)) < 1e-6))
% No controller state defined.
% Closed loop A matrix.
A = Ap + Bp*inv(Z)*Dc1*Cp;
% Closed loop B matrix.
B = Bp;
% Closed loop C matrix.
C = Cp;
% Closed loop D matrix.
D = Dp;
else
% Controller state defined.
% Closed loop A matrix.
A = [Ap + Bp*inv(Z)*Dc1*Cp, Bp*inv(Z)*Cc;
Bc1*(eye(size(DpiZDc1,1))+DpiZDc1)*Cp, Ac+Bc1*Dp*inv(Z)*Cc];
% Closed loop B matrix.
B = [Bp*inv(Z)*Dc2; Bc2 + Bc1*Dp*inv(Z)*Dc2];

Page 35

% Closed loop C matrix.


C = [(eye(size(DpiZDc1,1))+DpiZDc1)*Cp, Dp*inv(Z)*Cc];
% Closed loop D matrix.
D = Dp*inv(Z)*Dc2;
end

FREQUENCY ANALYSIS:
function [freq_data] = freq_analysis(sys_p, sys_c, w, i_in, i_out)
nf = numel(w);
% Extract plant matrices.
Ap = sys_p.Ap;
Bp = sys_p.Bp;
Cp = sys_p.Cp;
Dp = sys_p.Dp;
% Extract controller matrices.
Ac = sys_c.Ac;
Bc1 = sys_c.Bc1;
Bc2 = sys_c.Bc2;
Cc = sys_c.Cc;
Dc1 = sys_c.Dc1;
Dc2 = sys_c.Dc2;
% Initialize input frequency analysis substructure.
freq_data.input.Lin = zeros(nf,1);
freq_data.input.ReturnDiff= zeros(nf,1);
freq_data.input.StabRobust= zeros(nf,1);
freq_data.input.LoopGainXover_rps= 0;
freq_data.input.GMRD = [0,0];
freq_data.input.PMRD = [0,0];
freq_data.input.GMSR = [0,0];
freq_data.input.PMSR = [0,0];
freq_data.input.Gnoise = zeros(nf,1);
% Initialize output frequency analysis substructure.
freq_data.output.S = zeros(nf,1);
freq_data.output.T = zeros(nf,1);
% Initialize system substructure.
freq_data.system.OLEvalues = [];
freq_data.system.CLEvalues = [];
% Close the loop
Z = inv(eye(size(Dc1*Dp))-Dc1*Dp);
Acl = [(Ap+Bp*Z*Dc1*Cp)
(Bp*Z*Cc);
(Bc1*Cp+Bc1*Dp*Z*Dc1*Cp) (Ac+Bc1*Dp*Z*Cc)];
Bcl = [(Bp*Z*Dc2);
(Bc2+Bc1*Dp*Z*Dc2)];
Ccl = [(Cp+Dp*Z*Dc1*Cp) (Dp*Z*Cc)];
Dcl=(Dp*Z*Dc2);
%%%%% EIGENVALUE ANALYSIS %%%%%
% Compute the eignevalues of the open loop plant, and closed loop system.
freq_data.system.OLEvalues = eig(Ap);
freq_data.system.CLEvalues = eig(Acl);
%%%%% LOOP GAIN AT PLANT INPUT ANALYSIS %%%%%
%Create SS model of loop gain at the plant input.
Ain = [ Ap 0.*Bp*Cc; Bc1*Cp Ac];
Bin = [ Bp; Bc1*Dp];
Cin = -[ Dc1*Cp Cc];
Din = -[ Dc1*Dp];
% Perform frequency analysis for each input.

Page 36

L_in = zeros(nf,1);
RD_in= zeros(nf,1);
SR_in= zeros(nf,1);
Gnois= zeros(nf,1);
fori = 1:nf
% s = j*omega
s = sqrt(-1)*w(i);
% Controller object.
KK = Cc*inv(s*eye(size(Ac))-Ac)*Bc1+Dc1;
% Loop Gain.
L_in(i) = Cin(i_in,:)*inv(s*eye(size(Ain))-Ain)*Bin(:,i_in)+Din(i_in,i_in);
% Return difference.
RD_in(i) = 1.+L_in(i);
% Difference at actuator input.
SR_in(i) = 1.+1./L_in(i);
% Noise transfer function.
Gnois(i) = max(svd(KK));
end
% Compute crossover frequency.
magdb = 20.*log10(abs(L_in));
wc = FindCrossover(magdb,w);
% Compute the return difference and stability robustness MIMO margins.
rtd = 180/pi;
rdm = min(abs(RD_in));
srm = min(abs(SR_in));
rd_gm = [ (1/(1+rdm)) (1/(1-rdm)) ];
sr_gm = [ (1-rdm) (1+rdm) ];
rd_gm = 20*log10(rd_gm);
sr_gm = 20*log10(sr_gm);
rd_pm = rtd*2*asin(rdm/2);
sr_pm = rtd*2*asin(srm/2);
% Store.
freq_data.input.Lin = L_in;
freq_data.input.ReturnDiff= RD_in;
freq_data.input.StabRobust= SR_in;
freq_data.input.LoopGainXover_rps= wc;
freq_data.input.GMRD = rd_gm;
freq_data.input.PMRD = rd_pm;
freq_data.input.GMSR = sr_gm;
freq_data.input.PMSR = sr_pm;
freq_data.input.Gnoise = Gnois;
%%%%% LOOP GAIN AT PLANT OUTPUT ANALYSIS %%%%%
%SS model of loop gain at the plant output
Aout = [ ApBp*Cc; 0.*Bc1*Cp Ac];
Bout = [ Bp*Dc1; Bc1];
Cout = [ CpDp*Cc];
Dout = [ Dp*Dc1];
sens = zeros(nf,1);
compsens = zeros(nf,1);
fori = 1:nf
% s = j*omega
s = sqrt(-1)*w(i);
% Loop at Plant output (Az).
Lout = Cout(i_out,:)*inv(s*eye(size(Aout))-Aout)*Bout(:,i_in)+Dout(i_out,i_in);
% Sensitivity

Page 37

Sout = inv(eye(size(Lout))+Lout);
% Complementary sensitivity
Tout = Sout*Lout;
% Get max SV for each sensitivity.
sens(i) = max(svd(Sout));
compsens(i) = max(svd(Tout));
end
% Store.
freq_data.output.S = sens;
freq_data.output.T = compsens;

function t1 = FindCrossover(a,t)
%find the value of t where a crosses zero
n=numel(a);
j=0;
while j <= n,
if a(n-j) > 0.,
i=n-j;
j=n+1;
end;
j=j+1;
end
pp=inv([t(i) 1.;t(i+1) 1.])*[a(i);a(i+1)];
t1=-pp(2)/pp(1);

MODE ANALYSIS:
function [Msens, Mmetric] = perform_mode_analysis(A)
% Get the dimension of the square system matrix.
n = size(A,1);
% Initialize the output.
Msens = zeros(n,n);
Mmetric = zeros(3,n)-999;
% Compute the eigenvectors, V = [v1 v2 ... vn], for the system. Also
% returns an eigenvalue matrix, D, where the associated eigenvalues are
% down the main diagonal.
[V, D] = eig(A);
% Compute the inverse of matrix V.
Vinv = inv(V);
% Compute the sensitivities of each mode.
fori = 1:n
% Build a diagonal matrix of the ith column of the inverse eigenvector
% matrix.
C = diag(Vinv(:,i));
% Compute the modes of the ith state by multiplying the ith row of V by
% the diagonal matrix of Vinv. Take the magnitude in case the mode has
% a frequency component (i.e. imaginary value).
Msens(i,:) = abs(V(i,:)*C);
end
% Compute the metics of each mode. A complex conjugate pair will realize
% the same metrics.
fori = 1:n
% Compute the time to half amplitude.
thalf = log(1/2) / real(D(i,i));
% Store the time to half amplitude.
Mmetric(1,i) = thalf;

Page 38

% If this eigenvalue is real, then there is no frequency component.


wd = abs(imag(D(i,i)));
ifwd< 1e-6
continue
end
% Compute the period of the mode.
T = (2*pi)/wd;
% Store the period.
Mmetric(2,i) = T;
% Compute the ratio of time to half amplitude to the period.
Nhalf = thalf/T;
% Store the ratio.
Mmetric(3,i) = Nhalf;
end

FREQUENCY RESPONSE:
functionplot_freq_resp(freq_resp, w)
rtd = 180/pi;
% Extract data from frequency response structure.
L_in = freq_resp.input.Lin;
wc
= freq_resp.input.LoopGainXover_rps;
RD_in = freq_resp.input.ReturnDiff;
rd_min = min(abs(RD_in));
SR_in = freq_resp.input.StabRobust;
sr_min = min(abs(SR_in));
sens = freq_resp.output.S;
S_max = max(abs(sens));
compsens= freq_resp.output.T;
T_max = max(abs(compsens));
Gnois = freq_resp.input.Gnoise;
% Draw circles.
dd=0.:.001:2*pi;
xx1=cos(dd)-1;yy1=sin(dd);
xx2=rd_min*cos(dd)-1;yy2=rd_min*sin(dd);
% Nyquist plot
figure,
plot(xx1,yy1,'k',real(L_in),imag(L_in),'b',xx2,yy2,'r-','LineWidth',2);grid
axis([-2 2 -2 2]);
text(.5,.5,['radius = ' num2str(rd_min)])
xlabel('Re(L)')
ylabel('Im(L)')
title('Nyquist')
xw_plot = 2*min(w);
% Loop Gain Bode magnitude
figure
semilogx(w,20*log10(abs(L_in)),'LineWidth',2);grid
text(xw_plot,10.,['LGCF = ' num2str(wc)])
xlabel('Frequency (rps)')
ylabel('Magnitude dB')
title('Bode');
% Loop gain Bode phase
figure
semilogx(w,rtd*angle(L_in),'LineWidth',2);grid
xlabel('Frequency (rps)')
ylabel('Phase deg')
title('Bode');
% Plot Return Difference 1+L magnitude.

Page 39

figure
semilogx(w,20*log10(abs(RD_in)),'LineWidth',2);grid
text(xw_plot,10.,['min = ' num2str(rd_min)])
xlabel('Frequency (rps)')
ylabel('Magnitude dB')
title('|I+L| at input')
% Plot Stability Robustness 1+inv(L) magnitude.
figure
semilogx(w,20*log10(abs(SR_in)),'LineWidth',2);grid
text(xw_plot,10.,['min = ' num2str(sr_min)])
xlabel('Frequency (rps)')
ylabel('Magnitude dB')
title(' |I+inv(L)| at Plant Input')
% Plot sensitivity.
figure
semilogx(w,20*log10(sens),'LineWidth',2);grid
text(xw_plot,-10.,['max = ' num2str(S_max)])
xlabel('Frequency (rps)')
ylabel('Magnitude dB')
title(' |S| at Plant Output')
% Plot complementary sensitivity.
figure
semilogx(w,20*log10(compsens),'LineWidth',2);grid
text(xw_plot,-10.,['max = ' num2str(T_max)])
xlabel('Frequency (rps)')
ylabel('Magnitude dB')
title(' |T| at Plant Output')
% Plot noise to control magnitude.
figure
semilogx(w,20*log10(Gnois),'LineWidth',2);grid
xlabel('Frequency (rps)')
ylabel('Magnitude dB')
title('Noise-to-Control Transfer Function Matrix')

RUNGE KUTTA ALGORITHM


functionx_new = rk4(f, T_s, dt_s, x, u)
% Compute the derivative of the function.
xd = feval(f, T_s, x, u);
% Compute intermediate state value.
xa = xd*dt_s;
xi = x + 0.5*xa;
% Compute intermediate time value.
t_s = T_s + 0.5*dt_s;
% Compute the derivative using the intermediate values.
xd = feval(f, t_s, xi, u);
% Compute Runge-Kutta parameters.
q = xd*dt_s;
xi = x + 0.5*q;
xa = xa + 2.0*q;
xd = feval(f, t_s, xi, u);
q = xd*dt_s;
xi = x + q;
xa = xa + 2.0*q;
% Compute associated time.
t_s = t_s + dt_s;
% Compute the next state.
xd = feval(f, t_s, xi, u);
x_new = x + (xa + xd*dt_s)/6.0;

Page 40

Page 41

You might also like