Download as pdf or txt
Download as pdf or txt
You are on page 1of 445

Bahir Dar Institute of Technology

Lecture-1: MATLAB Function & Graphics

 Special operations
 Function
 2D Graphs
 3D Graphs

1
1.1 Special Operations
Element-by-element operations
operation operator
product: a.*b .*
division: a./b ./ or .\
power: a.^b .^
 Operations don't follow the rules of linear
algebra
 If operands are vector or matrix, they have the
same size.

2
1.1 Special Operations
Matrix-Matrix Operation

 a11 a12   b11 b12 


A  B 
a a
 21 22   b21 b22 
 a11  b11 a12  b12 
A.* B   
a 21  b21 a 22  b22 
 a11 / b11 a12 / b12 
A. / B   
a / b a
 21 21 22 22  / b

3
1.1 Special Operations
Matrix-Matrix Operation
 a11 a12  B   b11 b12 
A  b 
a 21 a 22   21 b22 
 a11 \ b11 a12 \ b12 
A. \ B   
a 21 \ b21 a 22 \ b22 
 a11 ^ b11 a12 ^ b12 
A. ^ B   
a 21 ^ b21 a 22 ^ b22 

4
1.1 Special Operations
Scalar-Matrix Operation
 b11 b12 
a: scalar B 
 b21 b22 
 a  b11 a  b12 
aB   
 a  b21 a  b22 
 a / b11 a / b12 
a. / B   
a / b21 a / b22 

5
1.1 Special Operations
Scalar-Matrix Operation
 b11 b12 
a: scalar B 
 b21 b22 
 b11 ^ a b12 ^ a 
B. ^ a   
b
 21 ^ a b 22 ^ a 
 a ^ b11 a ^ b12 
a. ^ B   
 a ^ b 21 a ^ b 22 

6
1.1 Special Operations
% Element-by-element product
>>A=[2 5; -2 3]
A= 2 5
-2 3
>>B=[4 4;1 2]
B= 4 4
1 2
>>C= A.*B
C= 8 20
-2 6
7

7
1.1 Special Operations
% Element-by-element division
>>A=[2 5; -2 3]
A= 2 5
-2 3
>>B=[4 4;1 2]
B= 4 4
1 2
>>C= A./B
C= 0.5000 1.2500
-2.0000 1.5000

8
1.1 Special Operations
% Element-by-element division
>>b= 2
b= 2
>>A=[2 5; -2 3]
A= 2 5
-2 3
>>C= b./A
C= 1.0000 0.4000
-1.0000 0.6667

9
1.1 Special Operations
% Element-by-element power
>>A=[2 5; -2 3]
A= 2 5
-2 3
>>B=[4 4;1 2]
B= 4 4
1 2
>>C= A.^B
C= 16 625
-2 9

10
1.1 Special Operations
% Element-by-element power
>>b= 2
b= 2
>>A=[2 5; -2 3]
A= 2 5
-2 3
>>C= b.^A
C= 4.0000 32.0000
0.2500 8.0000

11
1.1 Special Operations
% Element-by-element addition
>>b= 4
b= 4
>>A=[2 5; -2 3]
A= 2 5
-2 3
>>C= A+b
C= 6 9
2 7

12
1.1 Special Operations
Example 1: Obtain y= x2cos(x), where x= 0,1,2,3
>> x= 0:3;
>> y= x.^2.*cos(x)

Computation process
 x= [0 1 2 3]
 x.^2= [0 1 4 9]
 cos(x)= [1 0.5403 -0.4161 -0.9900]
 x.^2.*cos(x)= [0 0.5403 -1.6646 -8.9099]

13
1.1 Special Operations
Example 2: Plot y= sin(x)/x (-3x3)
>>x= -3*pi:pi/30:3*pi;
>>x= x+eps;
>>y= sin(x)./x; 1

>> plot(x,y)
0.5

-0.5
-10 -5 0 5 10

14
1.1 Special Operations
Example 3: Plot z= x2-y2 (-2  x,y  2)

clf
x= -2:0.1:2; y= x;
[X,Y]= meshgrid(x,y);
Z= X.^2-Y.^2;
surf(X,Y,Z);
xlabel('x'), ylabel('y')
zlabel('f(x,y)')

15
1.2 Function
MATLAB program files can be either script or
function m-files
Script m-files:
Simply contain a sequence of statements
Write codes using the supplied editor
Use the workspace memory (the memory
used by command window)
Performed in two ways (command window
or MATLAB editor)

16
1.2 Function
Script(test.m) Command Window

17
1.2 Function
Function m-files:
Start with the keyword function
Useful for repeated use without modification
as MATLAB built-in functions
Accept I/O arguments
Use their own local variables (different from
the workspace memory)
When they are saved, the file name should be
the same as the function name

18
1.2 Function
Function(addsq.m) Command Window

19
1.2 Function
Syntax of a Function
function oarg= fname(iarg1, iarg2)
function [oarg1,oarg2]= fname(iarg1, iarg2)
function fname(iarg1, iarg2)
function [oarg1,oarg2]= fname

% [] can be skipped if output argument is one


% [] or () can be skipped if there are no input
or output arguments
20
1.2 Function
Example 4: Code a function m-file which
returns mean and standard deviation of a
vector x
Mean
n
1
x 
n i 1
xi

Standard deviation
n
1

n i 1
xi2  x 2

21
1.2 Function
Function m-file Command window

22
1.2 Function
Example 5: Code a function which returns x, y
data for drawing a circle with a center (x0,y0)
and radius r

(x, y) x  x 0  r cos 
y  y0  r sin 

23
1.2 Function
Function m-file Calling function

3
2
1
0
-1
-2
-3
-2 0 2

24
1.2 Function
Example: Code a function program which
returns the values of g(x) and h(x) from input
vector x.
g ( x )  x12  x2
h( x )  2  x1  x22

25
1.2 Function
Function m-file Calling function

26
1.2 Function
Memory use
scripts and Workspace
command window memory

function 1 Local memory


Local memory
function 2
global memory
global variables

* Memory locations are different


27
1.2 Function
Global variables
global var1 var2

Variables in a function are separate from


those of other functions and the workspace.
However, if functions declare global
variables, they all share a single copy of
those variables.

28
1.2 Function
Script(test03.m) fun1.m
global freq m function ft= fun1(t)
freq= 2; m= 0.3; global freq
p= 10; ft= cos(2*pi*freq*t);
x= fun1(p)
y= fun2(p) fun2.m
function fx= fun2(x)
x= 1 global m
y= 0.0498 fx= exp(-m*x);

29
1.2 Function
Anonymous function
f= @(arg1, arg2) expression

Quick means of creating simple functions


without storing it to a file
Can be constructed either at the MATLAB
command line or in any function or script

30
1.2 Function
Example: Given two functions, f(x,y)= xy+y
and g(x)= 1-exp(-x2), find f(2,3) and g([1 2 3])

>>f= @(x,y) x*y+y;


>>z= f(2,3)
z= 9

>>g= @(x) 1-exp(-x.*x);


>>y= g([1 2 3])
y= 0.6321 0.9817 0.9999

31
1.2 Function
Function
function [oarg1,oarg2]= fname(iarg1, iarg2)

Used to code user-defined programs.


iarg1, iarg2 are input arguments and
oarg1,oarg2 are output arguments.
If there are no input/output arguments, [] or ()
can be omitted.

32
1.2 Function
Example: Code a function that returns the
mean and standard deviation of x= [1, 4, 6, 9].
>> [ave,dev]= ave_dev([1 4 6 9])
ave= 5
dev= 2.9155

function [ave,dev]= ave_dev(x)


n= length(x); sq= sum(x.^2);
ave= sum(x)/n;
dev= sqrt(sq/n-ave^2);

33
1.2 Function
Function function
function [oarg1,oarg2]= fname(fun,iarg1, iarg2)

Use the name of the function as an input to


another function(for example, fun)
It is called with @(for example, @fun)
Serves a wide variety of purposes (root finding,
integration, solving ODE, etc)
The format is similar with that of a function

34
1.2 Function
Trapezoidal Integral
b
S a
f ( x) dx  S1  S 2  ...  S n

h
 [ f ( x0 )  2 f ( x1 )  ...  2 f ( xn 1 )  f ( xn )]
2

35
1.2 Function
Example 6: Code the trapezoidal method for
approximating the following integrals and
compare it with MATLAB built-in function.
 /2
(1) S  0
1  x 2 dx
 /2
(2) S   sin( x) dx
0

36
1.2 Function
Command window Function function
>>a= 0; b= pi/2; %Trapezoidal integration
>>s= trapz(@f1,a,b) function s= trapz(fun,a,b)
s= 2.0777 h= 0.01; x= a:h:b;
y= fun(x);
>>s= trapz(@f2,a,b) s1= sum(y(2:end-1));
s= 0.9992 s=0.5*h*(y(1)+2*s1+y(end));

function y= f1(x) function y= f2(x)


y= sqrt(1+x.^2); y= sin(x);

37
1.3 2D Graphs
Plot
plot(x,y) % plots vector x vs vector y
plot(x,y,Specifier,PropertyName,Property
Value) % plots x vs y with options
h= plot(…) % plots graph and returns its
handle, where … means that it can be one
of the formats used previously

38
1.3 2D Graphs
Specifier
Character string made from elements less than
three (e.g. 'b:'  blue dotted line)
b blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star d diamond
y yellow v triangle(down) s square
k black
w white

39
1.3 2D Graphs
Properties
LineWidth- set the line width in points
MarkerSize- specify the size of the marker
in points

plot(x,y,'c+:') % plots a cyan dotted line with a


plus at each data point
plot(x,y,'LineWidth',2) % plot with line width
of 2 points

40
1.3 2D Graphs
t= 0:0.02:8;
y1= exp(-t).*sin(t);
y2= exp(-0.5*t).*cos(t);
plot(t,y1,'k',t,y2,'r:','linewidth',2)
1

0.5

-0.5
0 2 4 6 8

41
1.3 2D Graphs
Title and label
title('text') % adds text at the top
xlabel('text') %adds text beside the X-axis
ylabel('text') %adds text beside the Y-axis
gtext('text') % place text with mouse
grid on / off % adds(removes) grid lines
box on / off % adds(removes) a box

42
1.3 2D Graphs
t= 0:0.02:8;
y1= exp(-t).*sin(t);
y2= exp(-0.5*t).*cos(t);
plot(t,y1,'k',t,y2,'r:','linewidth',2)
xlabel('t'), ylabel('y1 & y2')
title('My graphs') 1 My graphs

gtext('y1')
0.5
grid on
y1 & y2

y1
0

-0.5
0 2 4 6 8
t

43
1.3 2D Graphs
Axis and legend
 axis([xmin xmax ymin ymax]) % sets
scaling for the x- and y-axes
 axis equal % sets tick mark increments on
the axes are equal in size
 axis square % makes the current axis box
square
 axis on/off % turns on(off) axis labeling
 legend('str1','str2') % display legend

44
1.3 2D Graphs
t= 0:0.02:8;
y1= exp(-t).*sin(t);
y2= exp(-0.5*t).*cos(t);
plot(t,y1,'k',t,y2,'r:','linewidth',2)
xlabel('t'), ylabel('y1 & y2')
legend('y1','y2','Location','NorthEast')
axis([0 8 -0.5 1]) 1
y1
y2
0.5
y1 & y2

-0.5
0 2 4 6 8
t

45
1.3 2D Graphs
Creating Axes
 subplot(m,n,p) % create axes in tiled
positions, where p is the position in mn
axes.
 subplot mnp % same as the above

1 2 position

3 4

5 6

46
1.3 2D Graphs
Contour Graph

contour(Z) % plots a contour of Z


contour(X,Y,Z) % plots a contour of Z at X
and Z
contour(X,Y,Z,n) % plots n contour lines of
Z at X and Z
contour(X,Y,Z,v) % plots a contour of Z at X
and Z at the level v

47
1.3 2D Graphs
Example 7: Draw the contour of the equation.
f ( x)  2 x13  4 x1 x23  10 x1 x2  x22 (0  x1 , x2  5)

x1= 0:0.1:5;
x2= x1;
[X1,X2]= meshgrid(x1,x2);
F= 2*X1.^3+4*X1.*X2.^3-
10*X1.*X2+X2.^2;
contour(X1,X2,F,[-4 -2 0 3 7
11 20 40 120 200 400])
colorbar

48
1.3 2D Graphs
Fill

fill(x,y,'c') % fills the 2D polygon of x and y


with color c
h= fill(x,y,'c') % draws a 2D polygon and
returns its handle

49
1.3 2D Graphs
t= [0: pi/4:2*pi]+pi/8;
x=cos(t); y=sin(t); STOP
hold on
fill(x,y,'r')
plot(0.9*x,0.9*y,'w','LineWidth',3)
text(-0.5,0,'STOP','Color', 'w', 'FontSize',18);
axis square off
hold off

50
1.3 2D Graphs
Patch
patch(x,y,c) % adds the filled 2D polygon
defined by vectors x and y with color c
patch('vertices',verts,'faces',faces,'facecolor','c')
% creates the patch by specifying the faces,
vertices and facecolor properties.

51
1.3 2D Graphs
x= [1 4 1];
10

y= [2 2 6];
8

patch(x,y,'g') 5

axis([0 10 0 10]) 3

0
0 2 4 6 8 10

verts= [1 2;4 2;1 6]; faces= [1 2 3];


patch('vertices',verts,'faces',faces,'facecolor','g')
axis([0 10 0 10])

52
1.3 2D Graphs
Home work 1: Make two MATLAB codes
which draw the following traffic signals.

(a) (b)

53
1.4 3D Graphs
Plot3
 plot3(x,y,z) % plots a 3D line graph with x, y
and z of the same length
 plot3(x,y,z,Specifier,PropertyName,Proper
tyValue) % plots a 3D line graph with
options
 h= plot3(…) % plots a 3D line graph and
returns its handle

54
1.4 3D Graphs
t= linspace(-pi,pi,200)+eps;
x= sin(t); y= cos(t);
r= x.^2+y.^2;
z= zeros(size(x));
plot3(x,y,z,'r','linewidth',2)
hold on Nero's crown
z= abs(sin(10*t)./(10*t));
plot3(x,y,z,'b','linewidth',3)
axis([-1.2 1.2 -1.2 1.2 -0.5 2])
hold off
axis off
55
1.4 3D Graphs
Meshgrid
 [X,Y]= meshgrid(x,y) % transforms the domain
specified by vectors x and y into arrays X and Y
 [X,Y]= meshgrid(x) % same as the above(y= x)

z y

x x

56
1.4 3D Graphs
>> x= 1:3; y= -1:1;
>> [X,Y]= meshgrid(x,y)
>> Z= X.^2+Y.^2
X=1 2 3 Y= -1 -1 -1
1 2 3 0 0 0
10
1 2 3 1 1 1
z5
Z= 2 5 10
1 4 9 0
1
2 5 10 0
3

y -1 1
2
x
57
1.4 3D Graphs
Mesh
 mesh(Z) % plots 3D mesh surface of Z
 mesh(X,Y,Z) % plots 3D mesh surface of Z
at X and Y(color is proportional to mesh
height)
 meshc(X,Y,Z) % plots 3D mesh surface /
2D contour of Z at X and Y
 meshz(X,Y,Z) % plots 3D mesh surface of
Z at X and Y with curtain

58
1.4 3D Graphs
0.5
x= -2:0.2:2; 0
[X,Y]= meshgrid(x); 0.5
2
2
F= X.*exp(-X.^2-Y.^2); 0
-2 -2
0

subplot 311 0.5


mesh(X,Y,F) 0

subplot 312 0.5


2
2
meshc(X,Y,F) 0
-2 -2
0

subplot 313 0.5


meshz(X,Y,F) 0
0.5
2
0 2
0
-2 -2

59
1.4 3D Graphs
Colormap

 colormap % displays the color look-up table


of the current window
 map= colormap % retrieves the current
colormap, which is a 643 matrix whose
column means RGB color intensities in the
range of 0~1.
 colormap(map) % sets the current figure's
colormap to map

60
1.4 3D Graphs
Color Intensities
>> colormap
0 0 0.5625
0 0 0.6250
0 0 0.6875

0.8125 1.0000 0.1875
0.8750 1.0000 0.1250 [0 0 0] is black,
0.9375 1.0000 0.0625 [1 1 1] is white,
[1 0 0] is pure red,
R G B
[.5 .5 .5] is gray
61
1.4 3D Graphs
Built-in Colormaps  autumn varies smoothly
from red, through orange, to
yellow
 bone is a grayscale colormap
with a higher value for the
blue component
 cool consists of colors that
are shades of cyan and
magenta. It varies smoothly
from cyan to magenta
 copper varies smoothly from
black to bright copper
62
1.4 3D Graphs
x= -2:0.2:2; hsv cool
[X,Y]= meshgrid(x); 0.5 0.5

F= X.*exp(-X.^2-Y.^2); 0 0
0.5 0.5
subplot 311 2
0
-2 -2
0
2 2
0
-2 -2
0
2

mesh(X,Y,F) 0.5 0.5

subplot 312 0 0

0.5 0.5
meshc(X,Y,F) 2
0
-2 -2
0
2
2
0
-2 -2
0
2

subplot 313 0.5 0.5

meshz(X,Y,F) 0
0
0.5

colormap cool
0.5 2
2 0 2
0 2 0
0 -2 -2
-2 -2

63
1.4 3D Graphs
Example 8: Draw the graph of Torus equation:
x=cos(u)(R+rcos(v))
y=sin(u)(R+rcos(v))
z=rsin(v) (0u,v2)
where R is the distance from the center (major
radius) and r is the minor radius (tube)

64
1.4 3D Graphs
R= 1; r= 0.5;
u= linspace(0,2*pi,30);
[U,V]= meshgrid(u);
X= cos(U).*(R+r*cos(V));
Y= sin(U).*(R+r*cos(V));
Z= r*sin(V);

mesh(X,Y,Z)
axis equal;
axis off
view(55,40)
65
1.4 3D Graphs
Surf

 surf(X,Y,Z) % plots a 3D colored surface


of Z at X and Y
 surfc(X,Y,Z) % displays a 3D colored
surfacesurf/contour plot
 surfl(X,Y,Z) % plots a 3D colored surface
with lighting
 shading interp/flat/faceted % controls the
color shading of surface(faceted: default)

66
1.4 3D Graphs
Example 9: Draw the mesh, surf, surfl graphs
of the following equation on the 13 tiled
axes
y= -5xyexp(-x2-y2) (-4x,y4)

67
1.4 3D Graphs
Other Commands
 view(az,el) % specifies 3D graph viewpoint.
az is the azimuth and el is the vertical
elevation(degree unit)
 colorbar % displays color bar (color scale)
 whitebg % changes axes background
color(toggle type)
 axis([xmin xmax ymin ymax zmin
zmax]) % sets the scaling for the x-, y- and
z-axes

68
1.4 3D Graphs
x= -2:0.2:2;
[X,Y]= meshgrid(x);
F= X.*exp(-X.^2-Y.^2);
surf(X,Y,F)
xlabel('x'); ylabel('y'); 0.4
zlabel('z=f(x,y)'); 0.5
0.2
colorbar
z=f(x,y)
0
0

colormap jet -0.5 -0.2


2
2
0 0 -0.4
y -2 -2 x

69
1.4 3D Graphs
Quiz 1: Draw the graphs of the following
equations:
z= f(x,1) y= 1
 f(x,y)= -x2-y2
 y= 1 2

 f(x,1)= -x2-1 -2

f(x,y)
(-2  x, y  2) -4

-6

-8
-2
-1 2
0
0
1
y 2 -2 x

70
1.4 3D Graphs
Quiz 2: Draw the contour and surf graphs of the
following function:
Z  e x1 (4 x12  2 x22  4 x1 x2  2 x2  1)

(-3  x1, x2  2)

71
1.4 3D Graphs
Quiz 3: Draw the contour and surf graphs of the
following function:
Z  3(1  x1 ) 2 exp(  x12  ( x2  1) 2 ) 
10(0.2 x1  x13  x25 ) exp( x12  x22 ) 
1
exp(( x1  1) 2  x22 )
3
(-4  x1, x2  4)

72
Q&A

73
Lecture-2: Mathematical Modeling of
Systems

 Modeling of systems
 State space model of systems
2.1 Modeling of Systems
Electric heater Controller
y(t)
Sensor

u(t) Actuator
(t)

Heater coil and


chamber
2.1 Modeling of Systems
Design procedure of control systems
Step 1 : Performance specification
Objective, stability, reliability, economical efficiency
and performance, such as Mp, tr, ts and .
Step 2 : Selection of components
The control system consists of a plant, a controller,
actuators, and sensors. The components are selected at
this stage. Due to the relationship between design
specifications, reliability, and price, appropriate
compromise is required.
2.1 Modeling of Systems
Step 3 : Modelling
Physical laws are applied to derive mathematical
relations between elements, which is called a model.
Model structure, order, and parameters are determined
through experiments and experience.

Step 4 : Design of a controller


The core algorithm that satisfies the design specification
is designed(PID control, state feedback control, adaptive
control, and intelligent control).
2.1 Modeling of Systems
Step 5 : Simulation and Analysis
Simulate the models on the computer and analyze the
performance. If performance is not satisfactory, repeat
the previous steps.

Step 6 : Implementation and experiment


If performance is satisfactory, experiments are carried
out on the actual system.
2.1 Modeling of Systems
We want to design an electric heater which can
control the temperature properly.
Can we get a mathematical equation that shows
similar dynamics without a real device (heater coil,
chamber, SCR, etc.)?

Yes, we can find by applying physical laws to each


control element. Covered in this section.
2.1 Modeling of Systems
qo(t)
Plant
qi(t)
u(t) (t)
Heat coil+
SCR
chamber

Model Sensor
y(t)
u(t) qi(t) (t)
+
Kscr
- 𝒎
qo(t)
Kscr, Tm, Ks : unknown
parameters Ks
y(t)
2.1 Modeling of Systems
How can we find the parameters of the mathematical
equation?

I/O signal data of the actual system are collected through


experiments and the parameters are determined using data
and a parameter estimation technique.
y(t)

u(t)
2.1 Modeling of Systems
u(t) y(t)
Actual system

ym(t) +
Model
-

e(t)
Algorithm

Apply the same input to both the actual system and the
model, and adjust the model parameters to minimize
the error between the two outputs.
2.1 Modeling of Systems
Disturbance

Reference control
temperature
Reference
+ input Output
Sensor  Actuator
Controller Plant

Output
sensor

A controller is designed with the knowledge of the


plant (controlled object).
2.1 Modeling of Systems
(Definition) Model
Refers to a series of mathematical expressions
that describe a physical system and is obtained by
applying the laws of physics to the system.
In general, one of its forms becomes
 Differential equation
 Partial differential equation
 Difference equation
 ARMA(auto regressive moving average)
2.1 Modeling of Systems
Y (s) 1
 G (s)  
U ( s ) Ms   s  k
2

Physical
laws
Transfer
function
System Model
State space

My(t )  u (t ) - ky (t ) - By (t ) x (t )  Ax (t )  Bu(t ), x (t0 )


where u (t )  F (t ) y (t )  Cx (t )  Du(t )
2.1 Modeling of Systems
Laplace Transform of functions

L  y (t )  Y ( s )
L  y (t )  sY ( s )
L  y (t )  s Y ( s )
 2

  1
L  y (t )dt  Y ( s )
s
L  y (t  L)  e Y ( s )
 Ls
2.1 Modeling of Systems
Transfer function representation

 Laplace transforms a system represented by


differential equations and expresses it as a polynomial
of s.
 All ICs are regarded as 0. (Demerit)

My(t )  u (t ) - ky (t ) - By (t )
Y (s) 1
G (s)  
U ( s ) Ms   s  k
2
2.1 Modeling of Systems
 I/O relationship can be expressed concisely with
block diagram.

U(s) 1 Y(s)
Ms 2   s  k
 System analysis and controller design can be done in
the frequency domain.
 Applicable only to linear, time invariant systems.
(Demerit)
2.1 Modeling of Systems
State space representation
 Concise representation of a system by introducing
state variables. All initial conditions(ICs) are
maintained.
My(t )  u (t ) - ky (t ) - By (t )
with y (t0 ), y (t0 ), u (t0 )
x (t )  Ax (t )  Bu (t ), x (t0 )
y (t )  Cx (t )  Du (t )
 Consider the internal variables of the system besides
I/O signals.
2.1 Modeling of Systems
 Controller design is possible with optimal design
concept.
 Applicable to linear/nonlinear, time- varying /time-
invariant systems.
 Complicated when I/O relation is expressed by block
diagram. (Demerit)
x (t )  Ax (t )  Bu(t ), x (t0 )
y (t )  Cx (t )  Du(t )
2.1 Modeling of Systems
State variables
Dynamic Eq: Time
x1 (t )  y (t )
x (t )  Ax (t )  Bu (t ), x (t0 )
x2 (t )  y (t )
y (t )  Cx (t )  Du (t )
Laplace ODE: Time
Transform
My(t )  u (t ) - ky (t ) - By (t )
TF: Frequency Inverse
Laplace
Y (s) Transform
G (s)   C ( sI - A) B  D
-1

U (s)
2.1 Modeling of Systems
Cautions for Modeling
A model may accurately describe the actual system, but
it may not. For example, a model is well represented for
certain (low frequency) inputs, but not for other (high
frequency) inputs.
The more complex the model, the more consistent it is
to the actual system, but the more difficult the controller
design is.
Therefore, the model must be able to represent the
dynamics of the system without too much complexity.
2.2 State Space Model of Systems

(Definition) State variable


The minimum set of variables that can fully
determine the system behavior at t>t0 from u(t),
tt0 and the variable information at t= t0.

State variables x1(t), x2(t), , xn(t),


Inputs u1(t), u2(t), , um(t),
Outputs y1(t), y2(t), , yp(t)
2.2 State Space Model of Systems
For convenience, the system is often described by a state
vector, an input vector, and an output vector.
 x1 (t ) 
 x (t ) 
State vector x (t )   2  n
  
 
 xn (t ) 
 u1 (t ) 
 u (t ) 
Input vector u(t )   2  m
  
 
 um (t ) 
2.2 State Space Model of Systems
 y1 (t ) 
 y (t ) 
Output vector y (t )    p
2

  
 
 y p (t ) 
There are a number of ways to represent a system as a
state equation because state variables can be defined
by the internal and output signals and their linearly
combination.
2.2 State Space Model of Systems
(Definition) General representation of linear/
nonlinear systems

x (t )= f[x(t), u(t), t] : State equation


y(t)= g[x(t), u(t), t] : Output equation

where f[x(t), u(t), t] and g[x(t), u(t), t] are function


vectors. Two equations are called dynamic equation.
2.2 State Space Model of Systems
Linear TimeVarying(LTV) system

The representation of LTV systems is


x (t )  A(t ) x (t )  B (t )u(t )
y (t )  C (t ) x (t )  D(t )u(t )

 a11 (t) a12 (t)  a1n (t)  b11 (t) b12 (t)  b1m (t) 
   
 a21 (t) a22 (t)  a2 n (t)  b (t) b (t)  b (t)
A(t )  , B (t )   21 22 2m 
         
   
 an1 (t) an 2 (t)  ann (t)  bn1 (t) bn 2 (t)  bnm (t) 
2.2 State Space Model of Systems

c11 (t) c12 (t)  c1n (t)   d11 (t) d12 (t)  d1m (t) 
c (t) c (t)  c (t)   d (t) d (t)  d (t) 
C (t )    , D(t )   21 
21 22 2n 22 2m
        
   
c p1 (t) c p 2 (t)  c pn (t)   d p1 (t) d p 2 (t)  d pm (t) 

Coefficient matrices are time functions


2.2 State Space Model of Systems
Linear Time-Invariant(LTI) system

The representation of LTV systems is


x (t )  Ax (t )  Bu(t )
y (t )  Cx (t )  Du(t )
 a11 a12  a1n  b11 b12  b1m 
a a  a  b b  
b2 m 
A  21 22 2n 
, B  21 22
       
   
 an1 an 2  ann  bn1 bn 2  bnm 
2.2 State Space Model of Systems

c11 c12  c1n   d11 d12  d1m 


c c  c  d d  d 
C  21 22 2n 
,D   21 22 2m 
       
   
c p1 c p 2  c pn   d p1 d p 2  d pm 

 Coefficient matrices are constants


2.2 State Space Model of Systems
Newton's second law
(translational movement)

Must be big enough to


overcome friction

 F (t )  m  a(t )
i
i

 m  
y (t )
2.2 State Space Model of Systems
Mechanical system

Applying Newton's second ky (t )   y (t )


law with F(t) as input and
y(t) as output,

F (t )  ky (t )   y (t )  My(t )

 F (t )
i  M  a (t ) k: Spring constant
i  : Viscous friction
coefficient
2.2 State Space Model of Systems
Letting F(t)= u(t) and rearranging gives
 k 1
y (t ) 
 y (t )  y (t )  u (t )
M M M

with ICs y (t0 ), y (t0 )


ky (t )   y (t )
If we define the state variables
as x1 (t )  y (t ), x2 (t )  y (t )
2.2 State Space Model of Systems
x1 (t )  y (t ), x2 (t )  y (t )
Differentiating both sides once and then
arranging them
x1 (t )  y (t )  x2 (t )
k  1
x2 (t )  
y (t )   y (t )  y (t )  u (t )
M M M
k  1
 x1 (t )  x2 (t )  u (t )
M M M
ICs x1 (t0 )  y (t0 ), x2 (t0 )  y (t0 )
2.2 State Space Model of Systems
State equation
x1 (t )  x2 (t )
k  1
x2 (t )   x1 (t )  x2 (t )  u (t )
M M M
ICs x1 (t0 )  y (t0 ), x2 (t0 )  y (t0 )

Output equation

y (t )  x1 (t )
2.2 State Space Model of Systems
State equation(vector form)

 x1 (t )   0 1   x1 (t )   0 
 x (t )     k / M     
  / M   x2 (t )  1/ M 
u (t )
 2  

ICs  x1 (t0 )   y (t0 ) 


 x (t )    y (t ) 
 2 0   0 
Output equation(vector form)
 x1 (t ) 
y (t )  1 0  
 x2 (t ) 
2.2 State Space Model of Systems
Dynamic equation(vector form)
x (t )  Ax (t )  Bu (t ), x (t0 )
y (t )  Cx (t )  Du (t )

where
 0 
1  0 
A  , B 
 k / M  / M  1/ M 
 x1 (t ) 
C  1 0 , D  0, x (t )   
 x2 (t ) 
2.2 State Space Model of Systems
Dynamic equation
x (t )  f [ x (t ), u (t ), t ], x (t0 )
y (t )  g[ x (t ), u (t ), t ]
where
 x2 (t ) 
f [ x (t ), u (t ), t ]   k  1 
 x1 (t )  x2 (t )  u (t ) 
 M M M 
g[ x (t ), u (t ), t ]  x1 (t )
2.2 State Space Model of Systems
Vehicle system
F(t) is the external force as input, y1(t) and y2(t) are the
output of each vehicle, M1 and M2 are the mass of each
vehicle, k is the spring constant and  is the viscous
friction coefficient. Applying Newton's second law
here


2.2 State Space Model of Systems

F (t )  k[ y1 (t )  y2 (t )]  [ y1 (t )  y 2 (t )]
 M 1 
y1 (t )
2.2 State Space Model of Systems

k[ y1 (t )  y2 (t )]  [ y1 (t )  y 2 (t )]  M 2 
y2 (t )
2.2 State Space Model of Systems
Letting F(t)= u(t), defining the state variables as follows
and differentiating both sides once

x1 (t )  y1 (t ) x1 (t )  y1 (t )
x2 (t )  y1 (t ) x2 (t )  
y1 (t )
x3 (t )  y2 (t ) x3 (t )  y 2 (t )
x4 (t )  y 2 (t ) x4 (t )  
y2 (t )
2.2 State Space Model of Systems
State equation
x1 (t )  y1 (t )  x2 (t )
k 
x2 (t )  
y1 (t )   x1 (t )  x2 (t )
M1 M1
k  1
 x3 (t )  x4 (t )  u (t )
M1 M1 M1

y1 (t )   k[ y1 (t )  y2 (t )] / M 1 

[ y1 (t )  y 2 (t )] / M 1  F (t ) / M 1
2.2 State Space Model of Systems
x3 (t )  y 2 (t )  x4 (t )
k  k
x4 (t )  
y2 (t )  x1 (t )  x2 (t )  x3 (t )
M2 M2 M2

 x4 (t )
y2 (t )  k[ y1 (t )  y2 (t )] / M 2
 M2
+[ y1 (t )  y 2 (t )] / M 2
Output equation
y1 (t )  x1 (t )
y2 (t )  x3 (t )
2.2 State Space Model of Systems
Dynamic equation
 0 1 0 0 
 k   0
-  k    1 
-
 M1 M1 M 1 M1   
x (t )    x (t )   M 1  u (t )
 0 0 0 1  
0

 k  k    
 - -   0 
 M 2 M2 M 2 M2 

1 0 0 0 
y (t )    x (t ) Initial vector x(t )
0 0 1 0  0
2.2 State Space Model of Systems
Newton's second law
(rotational movement)

 T (t )  J   (t )
i
i

 J  (t )

T: torque , J: Moment of inertia


: Angular acceleration, : Angle
2.2 State Space Model of Systems
Rotation system
Applying Newton's second law
yields where (t) is torque as input,

(t) is rotation angle as output, J is
moment of inertia,  is the
coefficient of viscous friction, k is
the modulus of elasticity.
2.2 State Space Model of Systems

 (t )  k (t )  (t )  J(t )
Letting (t)= u(t), and defining
the state variables as follows: (t )

x1 (t )   (t )
x (t )  (t )
2
k (t )
Differentiating both sides once gives
2.2 State Space Model of Systems
State equation
x1 (t )  (t )  x2 (t )
 k  1
x2 (t )   (t )   x1 (t )  x2 (t )  u (t )
J J J
 (t )  k (t )  (t )  J(t )
Output equation
y (t )   (t )  x1 (t )
2.2 State Space Model of Systems
Dynamic equation

x (t )  Ax (t )  Bu (t ), x (t0 )
y (t )  Cx (t )  Du (t )
where
 0 1  0
A k   , B   1 
    
 J J J 
C  1 0 , D  0
2.2 State Space Model of Systems

RLC circuit
Consider a circuit where u(t) is the voltage as input,
y(t) is the voltage as output, R is resistor, L is inductor,
and C is capacitor.

i(t)
2.2 State Space Model of Systems
Applying Kirchhoff's law of voltage and Ohm's law
gives
di (t ) 1
u (t )  Ri (t )  L   i (t )dt
dt C
1
y (t )   i (t )dt
C

i(t)
2.2 State Space Model of Systems
State variables State equation
1 1 1
x1(t)=  i (t ) dt , x1 (t )  i (t )  x2 (t )
C C C
x2(t)= i(t) di (t )
x2 (t ) 
dt
1 R 1

LC  i (t )dt  i (t )  u (t )
L L
1 R 1
  x1 (t )  x2 (t )  u (t )
di (t ) 1 L L L
Ri (t )  L   i (t )dt  u (t )
dt C
2.2 State Space Model of Systems
Output equation
1
y (t )   i (t )dt  x1 (t )
C
Dynamic equation
 1 
 0 C  0
x (t )    x (t )   1  u (t ), x (t0 )
- 1 - R   
 L  L 
L 
y (t )  1 0 x (t )
2.2 State Space Model of Systems
DC motor
u(t) is voltage as input, (t) is angle as output, i(t)
armature current, eb(t) is counter electromotive force, R
and L are equivalent resistance and inductor of armature
circuit, respectively, J is the moment of inertia and  is
the coefficient of viscous friction


2.2 State Space Model of Systems
Applying the Kirchhoff's law to the armature circuit
gives di (t )
u (t )  eb (t )  Ri (t )  L
dt
eb (t )  K b(t )
where Kb is constant
Applying Newton's law to the rotational system 
becomes
τ(t )  K t i (t )
τ(t )  (t )  J(t )
where Kt is constant
2.2 State Space Model of Systems
Defining the state variables as follows and
differentiating both sides once gives

x1 (t )   (t ) x1 (t )   (t )
x (t )  (t ) x (t )  (t )
2
2

x3 (t )  i (t ) di (t )
x3 (t ) 
dt
 di (t )
u (t )  K b (t )  Ri (t )  L
dt
K t i (t )  (t )  J(t )
2.2 State Space Model of Systems
The dynamic equation is
 
0 1 0   
  0
  Kt   
x (t )  0 - x (t )   0  u (t ), x (t0 )
 J J 
  1
Kb R  
0 - -  L
 L L
y (t )  1 0 0 x (t )
2.2 State Space Model of Systems
Exercise 1: The following figure shows a motorcycle
suspension system. Find the dynamic equation by
inputting wheel displacement r(t) and outputting y(t).

m2 y
Solution: v car
ks b
After separating the s u s p e n s io n
body and the wheel, m1 x
and applying Newton's
kw
second law gives T ir e R o a d s u r fa c e
r
I n e r tia l r e fe r e n c e
2.2 State Space Model of Systems
y   k s ( y  x)  b( y  x )
m2 
x  k s ( y  x)  b( y  x )
m1 
 kw ( x  r )
Defining the state variables and
differentiating both sides once gives
x1  y
x2  y
x3  x
x4  x
2.2 State Space Model of Systems
State variables y   k s ( y  x)  b( y  x )
m2 
x  k s ( y  x)  b( y  x )
m1 
x1  y  x2
ks  kw ( x  r )
b
x2  
y ( x1  x3 )  ( x2  x4 )
m2 m2
x3  x  x4
ks b kw
x4  
x ( x1  x3 )  ( x2  x4 )  (r  x3 )
m1 m1 m1
Output equation
y  x1
2.2 State Space Model of Systems
Rewriting the equations yields
x  Ax  Bu , x (t0 )
y  Cx  Du
where
 0 1 0 0 
 k  0
 s  b ks b  0
 m2 m2 m2 m2   
A ,B   0 
 0 0 0 1   
kw 
 ks b ks b  
     m1 
 m1 m1 m1 m1 
C  1 0 0 0 , D  0, u  r
2.2 State Space Model of Systems
Bernoulli's equation
h

x
2 2
P1 v P2 v
  h1  
1
 h2 2
Daniel Bernoulli  2g  2g
(1700-1782)
Kinetic energy, potential energy
2.2 State Space Model of Systems

P1,v1

P2,v2

P1 v12 P2 v22
  h1    h2
 2g  2g
 (v1  v2 )
2 2
P1  P2 
2g
2.2 State Space Model of Systems
1-tank system qi (t )
The head changes due to the
difference between input and S
h(t)
output flow rate. The
equilibrium equation of the h(t)
fluid is A

qo (t )

S h(t )  t[qi (t )  qo (t )]  qi,qo: flow rates

h(t): head S: tank cross section


A: pipe cross section
2.2 State Space Model of Systems
S h(t )  t[qi (t )  qo (t )] qi (t )

S
If t0, then h(t)

h(t ) dh(t ) h(t)


lim  A
t  0 t dt qo (t )
1
 [ qi (t )  qo (t )]
S 
2.2 State Space Model of Systems
From the Bernoulli's equation
qi (t ) Atmospheric
P1= 0
v1= 0 pressure
S
h(t) h1(t)= h(t)
P2= 0
h(t)
v2= ?
qo (t ) h2(t)= 0

P1 v12 P2 v22
  h1    h2 v2 (t )  2 gh(t )
 2g  2g
2.2 State Space Model of Systems
Therefore,
qo (t )  Av2 (t )  A 2 gh(t ) 

Combining two equations  and  yields

dh(t ) 1
 [ qi (t )  qo (t )]
dt S
1
 [ qi (t )  A 2 gh(t )]
S
2.2 State Space Model of Systems
State equation

dh(t ) 1
 [ qi (t )  A 2 gh(t )] : nonlinear
dt S
or 1
x (t )  [u (t )  A 2 gx(t )]
S
 f [ x(t ), u (t ), t ]
where x(t)= h(t), u(t)= qi(t)
1
f [ x(t ), u (t ), t ]  [u (t )  A 2 gx(t )]
S
2.2 State Space Model of Systems

Output equation

y (t )  h(t )  x(t )
or
y (t )  g[ x(t ), u (t ), t ]

where
g[ x (t ), u (t ), t ]  x(t )
2.2 State Space Model of Systems
2-tank system
qi (t )

S1
Input: qi(t) S2
h1(t)
Output: h2(t) h2(t)

h1(t) h2(t) A2
A1

q1 (t ) qo (t )

qi, q1, qo: flow rates


S1, S2: tank cross sections
A1, A2: pipe cross sections
2.2 State Space Model of Systems

The equilibrium qi (t )
equations of the fluid
for tank 1 and 2 are S1
S2
h1(t)
h2(t)

h1(t) h2(t) A2
A1

dh1 (t ) 1 q1 (t ) qo (t )
 [ qi (t )  q1 (t )] 
dt S1
dh2 (t ) 1
 [q1 (t )  qo (t )] 
dt S2
2.2 State Space Model of Systems
qi (t )
Applying the
Bernoulli's equation S1
S2
at each tank h1(t)
h2(t)
becomes
h1(t) h2(t) A2
A1

q1 (t ) qo (t )

q1 (t )  A1 2 g[h1 (t )  h2 (t )] 

qo (t )  A2 2 gh2 (t ) 
2.2 State Space Model of Systems
Defining state variables x1(t)= h1(t), x2(t)= h2(t) and
rearranging , ,  and  yields

Dynamic equation
dx1 (t ) A1 1
 2 g[ x1 (t )  x2 (t )]  u (t )
dt S1 S1
dx2 (t ) A1 A2
 2 g[ x1 (t )  x2 (t )]  2 gx2 (t )]
dt S2 S2
y (t )  x2 (t )
where u(t)= qi(t), x(t0)= [h1(t0) h2(t0)]T
Q&A
Lecture-3: State Space Representation of
ODEs and Transfer Functions

 State space representation of ODEs


 State space representation of TFs
 MATLAB ODE solvers
 Solving ODEs using RK4
3.1 State Space Rep. of ODEs
(Question) Is it possible to express the model
represented by differential equations or transfer
functions in the state space form?

(Answer)
 In the case of differential equations, it is possible
through defining state variables appropriately.
 In the case of transfer functions, it is possible through
rewriting them as differential equations and
transforming them into state space.
3.1 State Space Rep. of ODEs
Method 1

3rd-order ODE
y  a1 
 y  a2 y  a3 y  b0
u  b1u  b2u  b3u 
with ICs, 
y (t0 ), y (t0 ), y (t0 ), u(t0 ), u (t0 ), u (t0 )

Defining the differential operator as p= d/dt yields

dy/dt= py, d2y/dt2= p2y, d3y/dt3= p3y


3.1 State Space Rep. of ODEs

y  a1 
 y  a2 y  a3 y  b0
u  b1u  b2u  b3u 

Expressing Equation  in terms of p and arranging it


gives 3
( p  a1 p  a2 p  a3 ) y
2

 (b0 p  b1 p  b2 p  b3 )u
3 2

p ( y  b0u )  p ( a1 y  b1u )
3 2

 p ( a2 y  b2u )  ( a3 y  b3u )  0 
3.1 State Space Rep. of ODEs
p 3 ( y  b0u )  p 2 (a1 y  b1u )
 p ( a2 y  b2u )  (a3 y  b3u )  0 

Defining the state variables as


x1  y  b0u 
x2  p ( y  b0u )  (a1 y  b1u )
 px1  (a1 y  b1u ) 
x3  p ( y  b0u )  p (a1 y  b1u )  (a2 y  b2u )
2

 px2  (a2 y  b2u ) 


3.1 State Space Rep. of ODEs
p 3 ( y  b0u )  p 2 (a1 y  b1u )
 p ( a2 y  b2u )  (a3 y  b3u )  0 
x3  p ( y  b0u )  p (a1 y  b1u )  (a2 y  b2u )
2

 px2  (a2 y  b2u )

From Equation  and 


px3  ( a3 y  b3u )  0 
3.1 State Space Rep. of ODEs
x1  y  b0u 
x2  px1  (a1 y  b1u ) 

Substituting Equation  into , and rewriting gives


x2  px1  (a1 y  b1u )
px1  x2  (a1 y  b1u )
 x2  a1 ( x1  b0u )  b1u
or
x1   a1 x1  x2  (b1  a1b0 )u
3.1 State Space Rep. of ODEs
x1  y  b0u 
x3  px2  (a2 y  b2u ) 

Substituting Equation  into , and rewriting gives


x3  px2  ( a2 y  b2u )
px2  x3  ( a2 y  b2u )
 x3  a2 ( x1  b0u )  b2u
or
x2   a2 x1  x3  (b2  a2b0 )u
3.1 State Space Rep. of ODEs
x1  y  b0u 
px3  (a3 y  b3u )  0 

Substituting Equation  into , and rewriting gives


px3  ( a3 y  b3u )
  a3 ( x1  b0u )  b3u
  a3 x1  (b3  a3b0 )u
or
x3   a3 x1  (b3  a3b0 )u
3.1 State Space Rep. of ODEs
Therefore, the state equation is
x1   a1 x1  x2  (b1  a1b0 )u
x2   a2 x1  x3  (b2  a2b0 )u
x3   a3 x1  (b3  a3b0 )u
or
x  Ax  Bu
  a1 1 0  b1  a1b0 
A    a2 0 1  , B  b2  a2b0 
  a3 0 0   b3  a3b0 
3.1 State Space Rep. of ODEs
From Equation 
y  x1  b0u
Therefore, the output equation is
y  Cx  Du
where,
C  1 0 0 , D  b0
3.1 State Space Rep. of ODEs
Given the initial values

y (t0 ), y (t0 ), y (t0 ), u(t0 ), u (t0 ), u (t0 )
and from definition of the state variables
x1  y  b0u
x2  px1  ( a1 y  b1u )  p ( y  b0u )  ( a1 y  b1u )
 y  b0u  a1 y  b1u
x3  px2  ( a2 y  b2u )
 p ( y  b0u  a1 y  b1u )  a2 y  b2u
 
y  b0u  a1 y  b1u  a2 y  b2u
3.1 State Space Rep. of ODEs
With substituting t= t0 and arranging, the initial
conditions are obtained by

x1 (t0 )  y (t0 )  b0u (t0 )


x2 (t0 )  y (t0 )  b0u (t0 )  a1 y (t0 )  b1u (t0 )
x3 (t0 )  
y (t0 )  b0u(t0 )  a1 y (t0 )
 b1u (t0 )  a2 y (t0 )  b2u (t0 )
3.1 State Space Rep. of ODEs
nth-order ODE
(n) ( n 1)
y  a1 y  ...  an 1 y  an y
(n) ( n 1)
 b0 u  b1 u  ...  bn 1u  bn u
with ICs
( n 1) ( n 1)
y (t0 ),..., y (t0 ), y (t0 ), u (t0 ),..., u (t0 ), u (t0 )
3.1 State Space Rep. of ODEs
x  Ax  Bu
y  Cx  Du
where
  a1 1 0  0   b1  a1b0 
 a 0 1  0   b  a b 
 2   2 2 0 

A     , B    
   
  an 1 0 0  1  bn 1  an 1b0 
  an 0 0  0   bn  an b0 
C  1 0  0 0 , D  b0
3.1 State Space Rep. of ODEs
Consider an ODE y  a1 y  a2 y  b0u  b1u  b2u

y  2 y  4 y  u  2u
2 
with y (0)  0, y (0)  0.1, u (0)  u (0)  0
1,
Since a1= 1, a
2= 2, b 0= 0, b 1= 2 b2= 1
x  Ax  Bu
y  Cx  Du
  a1 1   1 1   b1  a1b0  1 / 2 
A    ,B     
  a2 0    2 0  b2  a2b0   1 
C  1 0 , D  b0  0
3.1 State Space Rep. of ODEs

From ICs y (0)  0, y (0)  0.1, u (0)  u (0)  0


ICs of the state variables are

x1 (t0 )  y (t0 )  b0u (t0 )  0.1


x2 (t0 )  y (t0 )  b0u (t0 )
 a1 y (t0 )  b1u (t0 )  1 0.1  0.1
3.1 State Space Rep. of ODEs

y  2 y  4 y  u  2u
2 
with y (0)  0, y (0)  0.1, u (0)  u (0)  0

 1 1  1 / 2   0.1
x    x  u , x (t 0 )   
 2 0   1   0.1
y  1 0 x
3.1 State Space Rep. of ODEs

Example 1: Obtain the dynamic equation.


y  3 
 y  4 y  
u  u  2u
with y (0)  0, y (0)  y (0)  0.2, u(0)  u (0)  u (0)  0

Solution: From the given equation


a1= 3, a2= 0, a3= 4, b0= 1, b1= -1, b2= 0, b3= 2

y  a1 
 y  a2 y  a3 y  b0
u  b1u  b2u  b3u
3.1 State Space Rep. of ODEs
Dynamic equation
x  Ax  Bu
y  3 
 y  4 y  
u  u  2u
y  Cx  Du
where   a1 1 0   3 1 0 
A    a2 0 1    0 0 1 
  a3 0 0   4 0 0 
 b1  a1b0   1  3  1  4 
B  b2  a2b0    0  0  1    0 
 b3  a3b0   2  4  1   2 
C  1 0 0 , D  b0  1
3.1 State Space Rep. of ODEs
ICs are
x1 (t0 )  y (t0 )  b0u (t0 )  0.2
x2 (t0 )  y (t0 )  b0u (t0 )  a1 y (t0 )
 b1u (t0 )  0.2  3  0.2  0.8
x3 (t0 )  
y (t0 )  b0u(t0 )  a1 y (t0 )
 b1u (t0 )  a2 y (t0 )  b2u (t0 )
 3  0.2  0  0.2  0.6
a1= 3, a2= 0, a3= 4, b0= 1, b1= -1, b2= 0, b3= 2
y (0)  0, y (0)  y (0)  0.2, u(0)  u (0)  u (0)  0

3.1 State Space Rep. of ODEs
Method 2

3rd-order ODE
y  a1 
 y  a2 y  a3 y  b0
u  b1u  b2u  b3u 
with ICs, 
y (t0 ), y (t0 ), y (t0 ), u(t0 ), u (t0 ), u (t0 )
Representing Equation  with the differential operator
gives
u
y  (b0 p  b1 p  b2 p  b3 ) 3
3 2

( p  a1 p 2  a2 p  a3 )
3.1 State Space Rep. of ODEs
u
Letting 3 2 =q
(p +a1p +a2p+a3)
(p3+a1p2+a2p+a3)q= u 
y= (b0p3+b1p2+b2p+b3)q 
Define the state variables as
x1= q
x2= pq
x3= p2q
3.1 State Space Rep. of ODEs
Differentiating both sides once, the state equation is

x1  pq  x2
x2  p 2 q  x3
x3  p 3 q   a3 q  a2 pq  a1 p 2 q  u
  a3 x1  a2 x2  a1 x3  u
(p3+a1p2+a2p+a3)q= u  state variables
x1= q
x2= pq
x3= p2q
3.1 State Space Rep. of ODEs
From Equation  and , the output equation is

y = b0 p 3 q  b1 p 2 q  b2 pq  b3 q
= b0 (u  a1 p 2 q  a2 pq  a3 q )  b1 p 2 q  b2 pq  b3 q
= (b3  a3b0 )q  (b2  a2b0 ) pq  (b1  a1b0 ) p 2 q  b0u
= (b3  a3b0 ) x1  (b2  a2b0 ) x2  (b1  a1b0 ) x3  b0u

(p3+a1p2+a2p+a3)q= u  state variables


y= (b0p3+b1p2+b2p+b3)q  x1= q
x2= pq
x3= p2q
3.1 State Space Rep. of ODEs
x  Ax  Bu
y  Cx  Du
where
 0 1 0  0 
A   0 0 1  , B   0 
  a3  a2  a1  1 
C  b3  a3b0 b2  a2b0 b1  a1b0  , D  b0
3.1 State Space Rep. of ODEs
Initial conditions

From the dynamic equation


y  Cx  Du
y  Cx  Du  C ( Ax  Bu )  Du
 CAx  CBu  Du
y  CAx  CBu  Du

 CA( Ax  Bu )  CBu  Du
 CA2 x  CABu  CBu  Du0
3.1 State Space Rep. of ODEs
Substituting t= t0 gives
y (t0 )  Cx (t0 )  Du (t0 )
y (t0 )  CAx (t0 )  CBu (t0 )  Du (t0 )
y (t0 )  CA2 x (t0 )  CABu (t0 )  CBu (t0 )  Du0 (t0 )

Rewriting becomes
1
 C   y (t0 )  Du (t0 ) 
x (t0 )   CA  

 (t0 )  CBu (t0 )  Du (t0 )
y 

CA2   
y (t0 )  CABu (t0 )  CBu (t0 )  Du(t0 ) 
3.1 State Space Rep. of ODEs
nth-order ODE
(n) ( n 1)
y  a1 y  ...  an 1 y  an y
(n) ( n 1)
 b0 u  b1 u  ...  bn 1u  bn u
with ICs
( n 1) ( n 1)
y (t0 ),..., y (t0 ), y (t0 ), u (t0 ),..., u (t0 ), u (t0 )
3.1 State Space Rep. of ODEs
x  Ax  Bu
y  Cx  Du
where
 0 1 0  0  0
 0 0 1  0    
 0
A       , B     , D  b0
   
 0 0 0  1  0
  an  an 1  an  2   a1  1 
C  bn  an b0 bn 1  an 1b0  b2  a2b0 b1  a1b0 
3.1 State Space Rep. of ODEs
Example 2: Obtain the dynamic equation.
y  3 y  2 y  2u  u

with y (0)  0, y (0)  1, u (0)  u (0)  0
Solution: From the given equation, a1= 3, a2= 2, b0= 0,
b1= , b2= 1
y  a1 y  a2 y  b0u  b1u  b2u

x  Ax  Bu
y  Cx  Du
 0 1  0 1 0 
A    ,B   
  a2  a1   2 3 1 
C  b2  a2b0 b1  a1b0   1 2 , D  b0  0
3.1 State Space Rep. of ODEs
ICs are y (0)  0, y (0)  1, u (0)  u (0)  0

0 1
CA  1 2     4  5 
 2 3 
1
C   y (t0 )  Du (t0 ) 
x (t0 )     
   0
CA 
y ( t )  CB u ( t 0 )  
Du (t )
0 
1
1 2   1  1   5  2   1   5 / 3 
          
  4  5 0
   3  4 1 0
   4 / 3 
3.2 State Space Rep. of TFs
nth-order TF
n 1
Y ( s ) b0 s  b1s    bn 1s  bn
n
 n n 1
U ( s ) s  a1s    an 1s  an
Taking inverse Laplace transform yields
(n) ( n 1)
y  a1 y  ...  an 1 y  an y
(n) ( n 1)
 b0 u  b1 u  ...  bn 1u  bn u with all zero ICs

Then, Method 1 or 2 can be applied to the ODE.


3.2 State Space Rep. of TFs
Example 3: Obtain a dynamic equation of the system
using Method 1. All initial values are 0.

u y

Solution: From the block diagram

( s  15s  50 s )Y ( s )  ( s  3)U ( s )
3 2

s Y ( s )  15s Y ( s )  50 sY ( s )  sU ( s )  3U ( s )
3 2
3.2 State Space Rep. of TFs
Taking inverse Laplace transform yields

y  15 
 y  50 y  u  3u
Thus,
a1= 15, a2= 50, a3= 0, b0= b1= 0, b2= 1, b3= 3

 15 1 0 0 
x   50 0 1  x  1  u , x (0)  0
 0 0 0   3 
y  1 0 0 x
3.2 State Space Rep. of TFs
Example 4: Obtain a dynamic equation of the system
using the state variables in the block diagram.

u x2 y=x1

Solution: From the block diagram

Y ( s )  X 1 ( s )  y (t )  x1 (t )
sX 1 ( s )  X 2 ( s )  x1 (t )  x2 (t )
( s  3) X 2 ( s )  2U ( s )  x2 (t )  3 x2 (t )  2u (t )
3.2 State Space Rep. of TFs
y (t )  x1 (t )
x1 (t )  x2 (t )
x2 (t )  3 x2 (t )  2u (t )

Therefore,

0 1  0 
x    x    u , x (0)  0
 0 3  2
y  1 0 x
3.3 MATLAB ODE Solvers

• [t,x]= ode45(fun,tspan,x0), where fun is a user-


defined function and tspan= [t0 tf], integrates the
system of nonstiff differential equations x'= f(t, x)
from t0 to tf with initial conditions x0.

• [t,x]= ode15s(fun,tspan,x0), where fun is a user-


defined function and tspan= [t0 tf], integrates the
system of stiff differential equations x'= f(t,
x) from t0 to tf with initial conditions x0.
3.3 MATLAB ODE Solvers
1. When t and x are only used, the user-defined
function fun can be coded as:

function xdot= fun(t,x)


xdot= zeros(5,1); % Initialize xdot here if its order
% is greater that or equal to 2
xdot(1)= ;
xdot(2)= ;

xdot(5)= ;
3.3 MATLAB ODE Solvers
2. When the use of additional variables(u1, u2, …) is
required, the user-defined function fun can be coded
as:
function xdot= fun(t,x,u1,u2)
xdot= zeros(5,1); % Initialize xdot here if its order
% is greater that or equal to 2
xdot(1)= ;
xdot(2)= ;

xdot(5)= ;
3.3 MATLAB ODE Solvers
Example 5: Consider the Lorenz's system where =10,
= 24, and = 2. Draw the response and phase plane
for 30 seconds.

x1   ( x2  x1 )
x2  (1    x3 ) x1  x2
x3  x1 x2  x3
with x1 (0)  10, x2 (0)  24, x3 (0)  2
Program:
3.3 MATLAB ODE Solvers
User-defined Function
function xdot= fun(t,x)
sigma= 10; lamda= 24; gamma= 2;
xdot= zeros(3,1);
xdot(1)= sigma*(x(2)-x(1));
xdot(2)= (1+lamda-x(3))*x(1)-x(2);
xdot(3)= x(1)*x(2)-gamma*x(3);

x1   ( x2  x1 )
x2  (1    x3 ) x1  x2
x3  x1 x2   x3
3.3 MATLAB ODE Solvers
Primary Function
function test01
x0= [10;24;2]; tspan= [0 30];
[t,x]= ode45(@fun,tspan,x0);
x1= x(:,1); x2= x(:,2); x3= x(:,3);
plot3(x1,x2,x3,'linewidth',1)
xlabel('x_1'), ylabel('x_2'); zlabel('x_3')
% plot(x1,x3,'linewidth',1)
% xlabel('x_1'), ylabel('x_3')
box on
grid on
3.3 MATLAB ODE Solvers
Time responses with   10,   24, and   2
20

x1 0

-20
0 10 20 30 40 50 60
20

x2 0

-20
0 10 20 30 40 50 60
40

x3 20

0
0 10 20 30 40 50 60
t
3.3 MATLAB ODE Solvers

Phase plots

x1-x2 plane x1-x2-x3 plane


3.3 MATLAB ODE Solvers
Example 6: Obtain the response of the van der Pol
equation for 3000 seconds.
x1  x2
x2   (1  x12 ) x2  x1

with = 1000, x1(0)= 2, x2(0)= 0.


Program: Since this equation is stiff, ode15s is used.
3.3 MATLAB ODE Solvers
User-defined Function
function xdot= fun(t,x,u)
mu= 1000;
xdot= zeros(2,1);
xdot(1)= x(2);
xdot(2)= mu*(1-x(1)^2)*x(2)-x(1);

x1  x2
x2   (1  x12 ) x2  x1
3.3 MATLAB ODE Solvers
Primary Function
function test02
x0= [2;0];
tspan= [0 3000];
[t,x]= ode15s(@fun,tspan,x0);
y= x(:,1);
plot(t,y,'linewidth',2)
xlabel('t')
ylabel('y(t)')
3.3 MATLAB ODE Solvers
Time responses for   1000
3.3 MATLAB ODE Solvers
Example 7: Obtain the unit step response of the system
for 10 seconds.
y  2 y  4 y  u  2u
2 
with y(0)= 0, y(0)= 0.1, u(0)= u(0)= 0

Program: From the previous results, the state space


form is
 1 1  1/ 2   0.1
x    x  u , x (0)   
 2 0   1   0.1
y  1 0 x
3.3 MATLAB ODE Solvers
User-defined Function
function xdot= fun(t,x,u)
xdot= zeros(2,1);
xdot(1)= -x(1)+x(2)+0.5*u;
xdot(2)= -2*x(1)+u;

An additional variable u is passed to the function.

 1 1  1/ 2  x1   x1  x2  0.5u


x    x  u
 2 0   1  x2  2 x1  u
3.3 MATLAB ODE Solvers
Primary Function
function test03
x0= [0.1;0.1]; tspan= [0 10];
u= 1;
[t,x]= ode45(@(t,y) fun(t,y,u),tspan,x0);
y= x(:,1);
plot(t,y,'linewidth',2)
xlabel('t'); ylabel('y(t)');
axis([0 10 0 1])
3.3 MATLAB ODE Solvers
Unit step response
1

0.8

0.6
y(t)

0.4

0.2

0
0 2 4 6 8 10
t
3.4 Solving ODEs Using RK4

• x= RK4(fun,t,x,u,h,para), returns the updated state x


of nonstiff systems x'= f(t,x,u) where fun is a user-
defined function, para is the variable for passing
additional variables if any.

function xdot= fun(t,x,u,para)


xdot= zeros(5,1); % Initialize xdot here if its order
% is greater that or equal to 2
xdot(1)= ;

xdot(5)= ;
3.4 Solving ODEs Using RK4
RK4 Function
function x= RK4(fun, t, x, u, h, par)
% Solves ODEs using the 4th-order Runge-Kutta method.
% Coded by Prof. G. Jin, ASTU
% X= RK4(FUN,T,X,U,H) updates variable X using the user-% defined
function FUN(T,X,U), time T, current variable X,
% input U and step size H
%
% X= RK4(FUN,T,X,U,H,PAR) updates variable X using
% FUN(T,X,U,PAR), time T, current variable X, input U,
% step size H and additional parameter vector PAR
%
if nargin < 5
error('Usage: xnew= RK4(fun, t, x, u, h); or RK4(fun, t, x, u, h, par);')
end
3.4 Solving ODEs Using RK4
if nargin == 5
k1= h*fun(t,x,u);
k2= h*fun(t+0.5*h,x+0.5*k1,u);
k3= h*fun(t+0.5*h,x+0.5*k2,u);
k4= h*fun(t+h,x+k3,u);
else
k1= h*fun(t,x,u,par);
k2= h*fun(t+0.5*h,x+0.5*k1,u,par);
k3= h*fun(t+0.5*h,x+0.5*k2,u,par);
k4= h*fun(t+h,x+k3,u,par);
end
x= x+(k1+2*(k2+k3)+k4)/6;
3.4 Solving ODEs Using RK4
Example 8: Obtain the unit step response of the
system for 10 seconds, where all ICs are 0 and the
step size h= 0.01.

U(s) X2(s) X1(s)

Controller
3.4 Solving ODEs Using RK4
Defining two state variables x1 and x2 as shown in the
figure, the plant and the controller equations can be
given by
Plant: x1  x2
x2  3 x2  u
y  x1
3
Controller: u  25( r  x1  x2 )
25
 25r  25 x1  3 x2
3.4 Solving ODEs Using RK4
Primary Function
function test04
t=0; x= [0;0]; r= 1; h= 0.01; loop= 1000;
buf= [t x(1)]; % Data storage buffer
for i=1:loop
u= 25*r-25*x(1)-3*x(2); % State feedback controller
x= RK4(@fun,t,x,u,h);
t= t+h;
buf= [buf; t x(1)];
end
plot(buf(:,1),buf(:,2),'linewidth',2)
xlabel('t'), ylabel('y(t)'), axis([0 10 0 1.5])
3.4 Solving ODEs Using RK4
User-defined Function
function xdot= fun(t,x,u)
xdot= zeros(2,1);
xdot(1)= x(2);
xdot(2)= -3*x(2)+u;

x1  x2
x2  3 x2  u
3.4 Solving ODEs Using RK4

Unit step response


3.4 Solving ODEs Using RK4
Example 9: The block diagram shows the disk head
position control system. Obtain a step response when
Ka= 100.
d
r e u m+ y
+ 5000 -
Ka
- 𝑠 1000
3.4 Solving ODEs Using RK4

Controller: u  K a ( r  y )
  1000m  5000u
Actuator: m
 20 1  0 
Linear motor: x    x    (m  d )
 0 0 1 
y  1 0 x
3.4 Solving ODEs Using RK4
Actuator
function xdot= actuator(t,x,u)
xdot= -1000*x+5000*u;

Linear motor m  1000m  5000u


function xdot= linearmotor(t,x,u)
d= 0; % zero disturbance
xdot= zeros(2,1);
xdot(1)= -20*x(1)+ x(2);
xdot(2)= u-d;
 20 1  0
x    x    (m  d )
 0 0 1 
3.4 Solving ODEs Using RK4
Primary Function
function test05
t= 0; r= 1; xa= 0; xm= [0;0]; Ka= 100; h= 0.001;
loop= 1000;
buf= [t xm(1)];
for i=1:loop
u= Ka*(r-xm(1));
xa= RK4(@actuator,t,xa,u,h);
xm= RK4(@linearmotor,t,xm,xa,h);
t= t+h;
buf= [buf; t xm(1)];
end
3.4 Solving ODEs Using RK4
plot(buf(:,1),buf(:,2),'b','linewidth',2)
axis([0 1 0 1.5])
grid on
Unit step response
1.5

0.5

0
0 0.2 0.4 0.6 0.8 1
3.4 Solving ODEs Using RK4
Simulink diagram
3.4 Solving ODEs Using RK4
Example 10: Consider the PI controller for the
mooring winch tensioning system. Obtain the step
response with two gains Kp= 0.73 and Ki= 0.2.
2𝑠 1
d 𝑠2 5𝑠 500
r e u y
+ 1500 + -
PI
- 𝑠2 5𝑠 500 q
3.4 Solving ODEs Using RK4
Mooring winch
3.4 Solving ODEs Using RK4

PI Controller

e(t )  r (t )  y (t )
t
u (t )  K p e(t )  K i  e()d 
0

Kp: Proportional gain, Ki: Integral gain


3.4 Solving ODEs Using RK4

Actuator

q  5q  500q  1500u


 x1   5 1   x1   0 
 x    500 0   x   1500  u
 2   2  
 x1 
q  1 0  
 x2 
3.4 Solving ODEs Using RK4

Angular/Angle
velocity

y  q  d x  q  d
State x y yx
variable
3.4 Solving ODEs Using RK4
Disturbance

d  5d  500d  2 y  y


 x1   5 1   x1   2 
 x    500     y
0   x2   1 
 2 
 x1 
d  1 0  
 x2 
3.4 Solving ODEs Using RK4
function test06
t= 0; h= 0.02; loop= 2000; r= 20; z= 0;
xa= [0;0]; xi= 0; xd= [0;0]; Kp= 0.73; Ki= 0.2;
buf= [t xi];
for i=1:loop
e= r-xi; z= z+h*e; u= Kp*e+Ki*z;
xa= RK4(@actuator,t,xa,u,h);
ui= xa(1)-xd(1);
xi= RK4(@integrator,t,xi,ui,h);
xd= RK4(@disturbance,t,xd,xi,h);
t= t+h;
buf= [buf; t xi];
end
3.4 Solving ODEs Using RK4
plot(buf(:,1),buf(:,2),'b','linewidth',2)
axis([0 h*loop 0 25])
function xdot= actuator(t,x,u)
xdot= zeros(2,1);
xdot(1)= -5*x(1)+x(2);
xdot(2)= -500*x(1)+1500*u;
function xdot= integrator(t,x,u)
xdot= u;
function xdot= disturbance(t,x,u)
xdot= zeros(2,1);
xdot(1)= -5*x(1)+x(2)+2*u;
xdot(2)= -500*x(1)+u;
3.4 Solving ODEs Using RK4
Step response

25

20

15

10

0
0 10 20 30 40
3.4 Solving ODEs Using RK4
Simulink diagram
Q&A
Lecture-4: Handle graphics and Commands
for Animation

 Handle graphics and graphic objects


 Handles and property changes
 Commands for Animation
 Examples of simple animation
4.1 Handle Graphics and Graphic Objects
What is Handle Graphics ?

 Object-oriented graphics system on which data


visualisation and GUI design are based
 Defines a set of graphics objects, such as Axes,
Line, Surface, and Text, and provides mechanisms
to manipulate the properties of these objects
 Objects are organized in a Graphics Object
Hierarchy
4.1 Handle Graphics and Graphic Objects

Graphics Object Hierarchy


4.1 Handle Graphics and Graphic Objects
4.1 Handle Graphics and Graphic Objects

Basic Objects
• Root- Top object, always exists when MATLAB
is running
• Figure- Window that contains axes, lines,
toolbars, menus, and so on.
• Axes- Coordinate system that contains the object
representing the data
• Image- Image object created
• Light- Light object using the light function
4.1 Handle Graphics and Graphic Objects

• Line- Lines that represent the value of data passed


to the plot function
• Patch- One or more polygons defined by the
coordinates of its vertices
• Rectangle- Rectangle object created
• Surface- Plots of matrix data created
• Text- Labels for axes tick marks and titles and so
on
4.1 Handle Graphics and Graphic Objects
How to create objects

 When you call a graphic command in a m-file or


hit it at the command line, objects are created
>> figure
>> axes
 Every MATLAB graphic may comprise of various
objects
 Different types of commands use different objects
to represent data
4.1 Handle Graphics and Graphic Objects

 Calling figure automatically produces Figure


object
Figure
>> figure
object
 Calling axes automatically
produces Figure and Axes
objects
>> axes Figure
object

Axes
object
4.1 Handle Graphics and Graphic Objects
 Calling image automatically produces Figure,
Axes, and Image objects
>> load mandrill
Image
>> image(X) object
>> colormap(map)

 Calling line automatically produces Figure, Axes


and Line objects
>> line([1 2 3],[4 7 3])
Line
object
4.1 Handle Graphics and Graphic Objects
 Calling patch automatically produces Figure, Axes,
and Patch objects
>> patch([1 2 1.5 1],[1 1 2 1],'b')
>> axis([0 3 0 3]) Patch
object
 Calling rectangle automatically
produces Figure, Axes, and
Rectangle objects
>> rectangle('position',[1 2 1.5 1])
>> axis([0 3 0 6])
Rectangle
object
4.1 Handle Graphics and Graphic Objects

 Calling surf automatically produces Figure, Axes,


and Surf objects
>> x=-1:0.2:1;
>> [X,Y]= meshgrid(x);
Surf
>> Z= X.^2-Y.^2; object
>> surf(X,Y,Z)
 Calling text automatically produces
Figure, Axes, and Text objects
>> text(0.5,0.5,'Hello!') Text
object
4.1 Handle Graphics and Graphic Objects

 Any high-level command such as plot creates


Figure, Axes, and Line objects
>> plot([1 3 5],[3 1 7],'o-','linewidth',3)

Figure
Line

Axes
4.2 Handles and Property Changes
What are handles ?
 Handles are numbers that uniquely identify every
object we create
 By knowing an object's handle, we can easily
access that object's properties and also modify
those properties
 Handle
Root: 0
Figure: n(integer number)
Others: x(floating-point number)
4.2 Handles and Property Changes

How to obtain an object's handle ?

Method 1. Upon creation of a graphic function


For example,

>>h= figure Handle of Figure


h= 2
>>h= line(x,y) Handle of Line
h= 180.0010
4.2 Handles and Property Changes
Method 2. Using utility functions
• gcf- handle of the current figure
• gca - handle of the current axis in the current figure
• gco - handle of the current object in the current figure
Current figure is the active, top figure among various
figures in the window

>> figure(1)
>> plot([1 3 5],[3 1 7],'o-','linewidth',3)
>> figure(2)
>> text(0.5,0.5,'Hello!')
Current Figure
4.2 Handles and Property Changes

t= 0:0.02:2*pi;
y1= sin(t);
y2= cos(t);
h= plot(t,y1,'k',t,y2,'b:','linewidth',2)
h(1): handle for sine
h = 0.0022
175.0012 h(2): handle for cosine
1

0.5

-0.5

-1
0 0.5 1 1.5 2
4.2 Handles and Property Changes

How to know what properties objects have?


 Each object possess properties that can be easily
modified for user customization
 To know the properties of an object, use
>> get(h) % shows the properties of object h
>> get(gca) % shows the properties of current
Axes object
4.2 Handles and Property Changes

t= 0:0.01:2; y1= sin(pi*t); y2= cos(pi*t);


h= plot(t,y1,'k',t,y2,'b:','linewidth',2);
get(h(1))

DisplayName: ''
Annotation: [1x1 hg.Annotation]
Color: [0 0 0]
LineStyle: '-'
LineWidth: 2
Marker: 'none'
MarkerSize: 6

4.2 Handles and Property Changes

How to access properties of objects


There are two ways to modify some properties of an
object:

Method 1. Use of set command


>> set(h) % Return a list of all user-settable
properties and their current values for object h
>> set(h,'PropertyName',PropertyValue)% Set
object h' property to a new value
4.2 Handles and Property Changes

t= 0:0.01:2;
y1= sin(pi*t);
y2= cos(pi*t);
h= plot(t,y1,'k',t,y2,'b:','linewidth',2);
set(h(1),'Color','r','linewidth',3)

1
red color and 3 points
0.5
width for h(1)
0

-0.5

-1
0 0.5 1 1.5 2
4.2 Handles and Property Changes
Method 2. Use of MATLAB's property editor
 Open the property editor
 Select an object modified in the figure window
using the mouse
 Set the property

If we run the program


again, the previously
changed properties are
resetted.
4.3 Commands for Animation

1. plot & set


 h= plot(x,y) % displays a x-y plot and returns the
handle h.
 set(h,XData,x,YData,y)% sets the value of the
properties, Xdata and Ydata, for the object with
handle h.
2. fill & set
 h= fill(x,y,c) % fills the 2D polygon defined by x
and y with color c.
 set(h,Xdata,x,Ydata,y)
4.3 Commands for Animation

r= 2;
hold on
fill([0 20 20 0 0],[0 0 20 20 0],'y')
plot([0 15],[0 15],'k','linewidth',5)
[x,y]= Circle(5,5,r);
gh= fill(x,y,'r');
axis equal, axis([0 20 0 20])
for i= 0:5:10
[x,y]= Circle(5+i,5+i,r);
set(gh,'XData',x,'YData',y)
drawnow, pause(1)
end
4.3 Commands for Animation

3. rectangle & set


 h= rectangle(Position,[x,y,wh,ht], Facecolor, c)
% draws a rectangle defined by [x,y,wh,ht] with
color c and returns the handle h. x and y determine
the location and wh and ht determine the size.
 set(h,Position,[x,y,wh,ht])

ht
y
wh
x
4.3 Commands for Animation
4. text & set
 h= text(x,y,string) % draws string at the x,y position
and returns the handle h.
 set(h,Position,[x y],String,string)
5. drawnow & pause
 drawnow % flushes the event queue and updates
the figure window.
 pause(n) % pauses for n seconds.
6. cla & axes(h)
 cla % clears current axis.
 axes(h) % makes the axis with handle h current.
4.3 Commands for Animation
7. num2str
 s= num2str(x) % converts numbers to a string.

8. Circle
[x,y]= Circle(x0,y0,r) % returns x-y data with the
orizin x0,y0 and radius r.
function [x,y]= Circle(x0,y0,r)
t= 0:pi/20:2*pi;
x= x0+r*cos(t);
y= y0+r*sin(t);
4.3 Commands for Animation

9. HCoil
 [x,y]= HCoil(x0,y0,L,r,N) % returns x-y data of a
horizontal coil with the orizin x0,y0, the length L,
the radius r and the coil turns N.

function [x,y]= HCoil(x0,y0,L,r,N)


t= [0:pi/50:(2*N-1)*pi]+3*pi/2;
xv= linspace(0,1,numel(t))+(sin(t)+1)/(2*N);
x= x0+L*xv/max(xv);
y= y0+r*cos(t);
4.3 Commands for Animation

10. VCoil
 [x,y]= VCoil(x0,y0,L,r,N) % returns x-y data of a
vertical coil with the orizin x0,y0, the length L, the
radius r and the coil turns N.

function [x,y]= VCoil(x0,y0,L,r,N)


t= [0:pi/50:(2*N-1)*pi]+3*pi/2;
yv= linspace(0,1,numel(t))+(sin(t)+1)/(2*N);
x= x0+r*cos(t);
y= y0+L*yv/max(yv);
4.4 Examples of Simple Animation
Example 4.1 Draw a graph for displying moving sin(x)
and cos(x) trajectories (0x4).
4.4 Examples of Simple Animation
Program:

% Scripts Example4_1
clf
x= 0;
hold on
gh1= plot(x, sin(x),'r.');
gh2= plot(x, cos(x),'b.');
axis([0 4*pi -2 2])
grid on
hold off
buf= [];
4.4 Examples of Simple Animation

for x= 0.1:0.1:4*pi
buf= [buf;x sin(x) cos(x)];
set(gh1,'xdata',buf(:,1),'ydata', buf(:,2))
set(gh2,'xdata',buf(:,1),'ydata', buf(:,3))
drawnow
pause(0.01)
end
4.4 Examples of Simple Animation
Example 4.2 Draw an animation graph for displying
the level of a tank with the bottom area S= 300[cm2]
and the inlet flow rate q= 100[cm3/sec].

Tank volume
t
V (t )   q ( )d
0

Tank level
V (t )
h(t ) 
S
4.4 Examples of Simple Animation
Program:
% Scripts Example4_2
clf
q= 100; S= 300; V= 0; dt= 0.1;
x0= 10; y0= 0; width= 10; height= V/S;
if height <= 0
height= eps;
end
hold on
plot([10 10 20 20],[30 0 0 30],'linewidth',2)
gh= rectangle('Position',[x0 y0 width height], 'FaceColor', 'g');
axis([0 30 0 40])
4.4 Examples of Simple Animation

ylabel('h(t)')
hold off

for t= 0:dt:50
V= V+q*dt;
height= V/S;
set(gh,'Position',[x0 y0 width height])
drawnow
end
4.4 Examples of Simple Animation
Example 4.3 Draw an animation graph of a vertical
coil moving up and down where the radius r is 0.5 and
coil turns N is 10.
4.4 Examples of Simple Animation
Program:
% Scripts Example4_3
clf
hold on
x0= 0; y0= -0.5; L0= 1; r= 0.5; N=10;
plot([-1 1],[0 0],'k','linewidth',2)
plot([0 0],[x0 y0],'k')
[x,y]= VCoil(x0,y0,-L0,r,N);
gh= plot(x,y,'b');
axis equal
axis([-2 2 -3 1])
hold off
4.4 Examples of Simple Animation

for t= 0:0.1:20
L= L0+ 0.5*sin(t);
[x,y]= VCoil(x0,y0,-L,r,N);
set(gh,'ydata',y)
drawnow
pause(0.1)
end
4.4 Examples of Simple Animation
Example 4.4 Draw a moving marker between -1 and 1.
4.4 Examples of Simple Animation
Program:
% Scripts Example4_4
clf
hold on
plot([0 0],[-1 1],'k','LineWidth',2)
plot([0 0.1 0 0 0.1 0 0 0.1],[1 1 inf 0 0 inf -1 -1],'k')
text(0.2,-1,num2str(-1,'%2d'))
text(0.2,0,num2str(0,'%2d'))
text(0.2,1,num2str(1,'%2d'))
gh= fill([0 -0.5 -0.5 0],[0 0.3 -0.3 0],'g');
axis([-2 2 -2 2])
hold off
4.4 Examples of Simple Animation

for t= 0:0.02:4*pi
y= [0 0.3 -0.3 0]+sin(t);
set(gh,'YData',y)
drawnow
pause(0.01)
end
4.4 Examples of Simple Animation
Example 4.5 Draw a graph of rotating a disk with
diameter D= 1 where the radius d of the small circles
are 0.1 and 0.05, respectively and the black marker
has appropriate dimension.

(D-d)sin


(D-d)cos
4.4 Examples of Simple Animation
Program:
% Scripts Example4_5
clf
D= 1; d= 0.1; r= D-d;
hold on
fill([1.1 1.3 1.3 1.1],[0 -0.1 0.1 0],'k');
[x,y]= Circle(0,0,D); fill(x,y,'b');
[x,y]= Circle(0,0,d/2); fill(x,y,'w');
[x,y]= Circle(r,0,d); gh1= fill(x,y,'w');
[x,y]= Circle(-r,0,d); gh2= fill(x,y,'w');
axis equal
axis([-2 2 -2 2])
hold off
4.4 Examples of Simple Animation

for th= 0:pi/20:6*pi


x0= (D-d)*cos(th); y0= (D-d)*sin(th);
[x,y]= Circle(x0,y0,d);
set(gh1,'XData',x,'YData',y)
x0= (D-d)*cos(th+pi); y0= (D-d)*sin(th+pi);
[x,y]= Circle(x0,y0,d);
set(gh2,'XData',x,'YData',y)
drawnow
pause(0.05)
end
4.4 Examples of Simple Animation
Example 4.6 Draw a pendulum which is moving
between the angle of -/4 and /4, where the
pendulum length L is 2.

-Lcos 
L

Lsin
4.4 Examples of Simple Animation
Program:
% Scripts Example4_6
clf
L= 2; D= 0.3; d= 0.1; th= 0;
hold on
plot([-2 2],[0 0],'k','LineWidth',2);
[x,y]= Circle(0,0,d); fill(x,y,'r');
x0= L*sin(th); y0= -L*cos(th);
gh1= plot([0 x0],[0 y0],'b','LineWidth',2);
[x,y]= Circle(x0,y0,D);
gh2= fill(x,y,'r');
axis equal, axis([-2 2 -3 1])
hold off
4.4 Examples of Simple Animation

for t= 0:0.1:6*pi
th= pi/4*sin(t);
x0= L*sin(th); y0= -L*cos(th);
set(gh1,'XData',[0 x0],'YData',[0 y0])
[x,y]= Circle(x0,y0,D);
set(gh2,'XData',x,'YData',y)
drawnow
pause(0.05)
end
4.4 Examples of Simple Animation

Example 4.7 Given the trajectory of a cycloid curve,


draw the animation graph.
x= r(-sin)
y= r(1-cos) (0 4 and r= 1)
4.4 Examples of Simple Animation
Program:
% Scripts Example4_7
clf
th= 0; r= 1;
hold on
plot([-3 15],[0 0],'k','LineWidth',2)
x0= r*(th-sin(th)); y0= r*(1-cos(th));
gh1= plot(x0,y0,'-.b');
[x,y]= Circle(x0,y0,r/5); gh2= fill(x,y,'b');
[x,y]= Circle(r*th,r,r); gh3= fill(x,y,'r');
[x,y]= Circle(r*th,r,r/10); gh4= fill(x,y,'w');
axis equal
4.4 Examples of Simple Animation

axis([-1 15 -1 4])
hold off

buf= [];
for th= 0:0.1:4*pi
x0= r*(th-sin(th)); y0= r*(1-cos(th));
buf= [buf;x0 y0];
set(gh1,'XData',buf(:,1),'YData',buf(:,2))
[x,y]= Circle(x0,y0,r/5);
set(gh2,'XData',x,'YData',y)
[x,y]= Circle(r*th,r,r);
set(gh3,'XData',x,'YData',y)
4.4 Examples of Simple Animation

[x,y]= Circle(r*th,r,r/10);
set(gh4,'XData',x,'YData',y)
drawnow
pause(0.03)
end
Q&A
Lecture-5: Animation of Dynamic Systems

 Animation of mechanical systems


 Animation of electrical systems
 Animation of hydraulic systems
 Animation of a model car system
5.1 Animation of Mechanical Systems
Example 5.1 Consider a PI control system that
controls the rotation angle of a pendulum system.
Pendulum model:
   g 1
 (t )  2
 (t )  sin  (t )  2
u (t )
ML L ML
or L
x1 (t )  x2 (t )
g  1
x2 (t )   sin x1 (t )  x (t ) 
2 2 2
u (t )
L ML ML
y  x1 (t )
with state variables x1 (t )   (t ) and x2 (t )  (t )
5.1 Animation of Mechanical Systems
where M= 1[kg], L= 1.5[m], = 1[N.m.sec/rad], and
g= 9.8[m/sec2].

PI controller:

The PI controller is given by the following equation.


u (t )  K p e(t )  K i e(t )dt
where e(t)= r(t)-(t), r(t)= /4[rad] t0, Kp= 3, Ki= 2.

(1) Plot the angle response of the system for 15[sec]


where the initial vector x(0)= [0 0]T and h= 0.02[sec].
5.1 Animation of Mechanical Systems
Program: Example5_1
function Example5_1_1
clf
Kp= 3; Ki= 2; % PI controller gains
t= 0; h= 0.02; z= 0; loop= 750;
x= [0;0]; % Initial state vector
r= pi/4; % Set-point [rad]

buf= [t x(1)];
for i= 1:loop
e= r-x(1); % Compute e(t)
z= z+e*h; % Integral of e(t)
u= Kp*e+Ki*z; % PI control
5.1 Animation of Mechanical Systems

x= RK4(@fun,t,x,u,h);
t= t+h;
buf= [buf;t x(1)];
end
plot(buf(:,1),180/pi*buf(:,2),'k','linewidth',2); % Draw the angle
axis([0 h*loop 0 50])
xlabel('t[sec]'), ylabel('\theta(t)')

% The pendulum
function xdot= fun(t,x,u)
M= 0.5; mu= 0.9; g= 9.8; L= 1.5; % Parameters
xdot= zeros(2,1);
xdot(1)= x(2);
xdot(2)= -g*sin(x(1))/L-mu*x(2)/(M*L*L)+u/(M*L*L);
5.1 Animation of Mechanical Systems

x0= [0 0]T, r(t)= /4[rad] t0


5.1 Animation of Mechanical Systems
(2) Animate the PI control system for 15[sec].
Program: Example5_1
function Example5_1_2
clf
global L
t= 0; h= 0.02; z= 0; loop= 700;
x= [0;0]; % Initial state vector
r= pi/4; % Set-point
L= 1.5; % Length of the pendulum
D= 0.2; d= D/5; % Radius of circles
hold on
plot([-1 1],[0 0],'LineWidth',3) % Draw the horizontal rod
[xv,yv]= Circle(0,0,d); fill(xv,yv,'r'); % Draw the hinge
5.1 Animation of Mechanical Systems

x0= L*sin(x(1)); y0= -L*cos(x(1));


gh1= plot([0 x0],[0 y0],'k'); % Draw the pendulum
[xv,yv]= Circle(x0,y0,D);
gh2= fill(xv,yv,'r'); % Draw the mass
axis equal
axis([-2 2 -2 1])
hold off
for i= 1:loop
e= r-x(1); % Compute e(t)
z= z+e*h; % Integral of e(t)
u= 3*e+2*z; % PI control
x= RK4(@fun,t,x,u,h);
t= t+h;
x0= L*sin(x(1)); y0= -L*cos(x(1));
5.1 Animation of Mechanical Systems

set(gh1,'XData',[0 x0],'YData',[0 y0]) % Update gh1 with new x0 and y0


[xv,yv]= Circle(x0,y0,D);
set(gh2,'XData',xv,'YData',yv) % Update gh2 with new xv and yv
drawnow
pause(0.01)
end

% The pendulum
function xdot= fun(t,x,u)
global L
M= 0.5; mu= 0.9; g= 9.8; % Parameters
xdot= zeros(2,1);
xdot(1)= x(2);
xdot(2)= -g*sin(x(1))/L-mu*x(2)/(M*L*L)+u/(M*L*L);
5.1 Animation of Mechanical Systems

x0= [0 0]T, r(t)= /4[rad] t0


5.1 Animation of Mechanical Systems
Example 5.2 Consider an inverted pendulum-cart
system shown in the figure. When defining x1(t)= y(t),
x2(t)= y(t), x3(t)= (t), x4(t)= (t) as state variables, u(t)
as input, and y(t) as output, the dynamic equation is
given by
5.1 Animation of Mechanical Systems
Model:
0 1 0 0  0 
 x1   mg   x1   1 
 x   0 0 - 0   
 2   M   x2   M 
 u
 x3   0 0 0 
1  x3  0 
      
 x4   0 ( M  m) g   x4   1 
 0 0  
M   M  
y  1 0 0 0 x
where M= 3[kg], m= 0.01[kg], ℓ= 1[m], and
g= 9.8[m/sec2].
5.1 Animation of Mechanical Systems

The state feedback control to stabilize the inverted


pendulum-cart system while positioning the cart at the
desired point is as follows:

State feedback controller:

u= -18.367(r-x1)+18.980x2+98.265x3+31.980x4

(1) Plot y(t) and (t) for 5[sec] with x(0)= [1, 0, /4, 0]T
h= 0.02, and a set point r= -1.
5.1 Animation of Mechanical Systems
Program: Example5_2
function Example5_2_1
clf
t= 0; h= 0.02; loop= 200; r= -1; % Set-point
x= [1;0;pi/4;0]; % Initial state vector
buf= [t x(1) x(3)];

for i= 1:loop
u= -18.367*(r-x(1))+18.980*x(2)+98.265*x(3)+31.980*x(4);
x= RK4(@fun,t,x,u,h);
t= t+h;
buf= [buf;t x(1) x(3)];
end
5.1 Animation of Mechanical Systems

plot(buf(:,1),buf(:,2),buf(:,1),buf(:,3),'k','linewidth',2);
axis([0 h*loop -2 4])
xlabel('t[sec]'), ylabel('y(t) and \theta(t)')

% Pendulum-cart system
function xdot= fun(t,x,u)
M= 1; m= 0.01; g= 9.8; L= 1;
xdot= zeros(4,1);
xdot(1)= x(2);
xdot(2)= -m*g*x(3)/M+u/M;
5.1 Animation of Mechanical Systems

x(0)= [1, 0, /4, 0]T and r= -1, t0


5.1 Animation of Mechanical Systems
(2) Animate the state feedback control system.
Program: Example5_2
function Example5_2_2
clf
global L
L= 1; wd= 1.5; ht= 0.5; % Cart and pole dimension
y0= 0; % y coordinate of the hinge
t= 0; h= 0.02; loop= 200; r= -1; % Set-point
x= [1;0;pi/4;0]; % Initial state vector

hold on
plot([-3 3],[-0.7 -0.7],'LineWidth',3) % Draw the base
[xv,yv]= DrawCart(x(1),y0,wd,ht);
5.1 Animation of Mechanical Systems

gh1= fill(xv,yv,'g'); % Draw the cart


[xv,yv]= Circle(x(1)-wd/3,y0-ht,0.15);
gh2= fill(xv,yv,'r'); % Draw the front wheel
[xx,yy]= Circle(x(1)+wd/3,y0-ht,0.15);
gh3= fill(xx,yy,'r'); % Draw the rear wheel
[xx,yy]= Circle(x(1),y0,0.05);
gh4= fill(xx,yy,'r'); % Draw the hinge
xp= x(1)+L*sin(x(3)); yp= L*cos(x(3));
gh5= plot([x(1);xp],[y0;yp]);%Draw the rod
[xx,yy]= Circle(xp,yp,0.25);
gh6= fill(xx,yy,'r');% Draw the mass
gh7= text(-2,2.5,'x_1= '); % Draw text
gh8= text(-2,2.0,'x_3= '); % Draw text
5.1 Animation of Mechanical Systems

axis equal
axis([-3 3 -3 3])
hold off

for i= 1:loop
u= -18.367*(r-x(1))+18.980*x(2)+98.265*x(3)+31.980*x(4);
x= RK4(@fun,t,x,u,h);
t= t+h;
[xx,yy]= DrawCart(x(1),y0,wd,ht);
set(gh1,'XData',xx,'YData',yy) % Update handle gh1
[xx,yy]= Circle(x(1)-wd/3,y0-ht,0.15);
set(gh2,'XData',xx,'YData',yy) % Update handle gh2
[xx,yy]= Circle(x(1)+wd/3,y0-ht,0.15);
set(gh3,'XData',xx,'YData',yy) % Update handle gh3
5.1 Animation of Mechanical Systems

[xx,yy]= Circle(x(1),y0,0.05);
set(gh4,'XData',xx,'YData',yy) % Update handle gh4
xp= x(1)+L*sin(x(3)); yp= L*cos(x(3));
set(gh5,'XData',[x(1);xp],'YData',[y0;yp]) % Update handle gh5
[xx,yy]= Circle(xp,yp,0.25);
set(gh6,'XData',xx,'YData',yy) % Update handle gh6
set(gh7,'String',['x_1= ',Mynum2str(x(1))]); % Update handle gh7
set(gh8,'String',['x_3= ',Mynum2str(x(3))]); % Update handle gh8
drawnow
pause(0.01)
end
5.1 Animation of Mechanical Systems
% Pendulum-cart system
function xdot= fun(t,x,u)
global L
M= 1; m= 0.01; g= 9.8;
xdot= zeros(4,1);
xdot(1)= x(2);
xdot(2)= -m*g*x(3)/M+u/M;
xdot(3)= x(4);
xdot(4)= g*(M+m)*x(3)/(M*L)-u/(M*L);
% Data for drawing a cart
function [xx,yy]= DrawCart(x,y,wd,ht)
wd2= wd/2;
xx= [x-wd2;x-wd2;x+wd2;x+wd2;x-wd2];
yy= [y;y-ht;y-ht;y;y];
5.1 Animation of Mechanical Systems

x(0)= [1, 0, /4, 0]T and r= -1, t0


5.2 Animation of Electrical Systems
Example 5.3 Consider a RLC circuit with u(t) as input
and y(t) as output.

From the RLC circuit,


1
u  Ri1 
C1 
(i1  i2 ) dt
R= 1[]
1 di2 1
 
(i2  i1 )dt  L  i2 dt  0 L= 1[H]
C1 dt C2 C1= 1[F]
1 C2= 1[F]
y
C2 
i2 dt
5.2 Animation of Electrical Systems
Defining the state variables as x1(t)= i1(t) , x2(t)=
i2(t) , x3(t)= i2(t) gives the following equations:
 1 1  1
 - 0
 x1   RC1 RC1  x1   R 
 x    0    
 2  0 1   x2    0  u
 x3   1    
1 1   x3  0
-(  ) 0  
 LC1 LC1 LC2   
 x1 
 1  
y  0 0   x2 
 C2  x 
 3
5.2 Animation of Electrical Systems
(1) When the step-type input voltage u(t)= 0.76 [V]
t0 is applied, plot the output voltage y(t) for 20[sec]
where x(0)= 0 and h= 0.02 [sec].

Program: Example5_3
function Example5_3_1
clf
global C2

t= 0; h= 0.02; loop= 1000;


C2= 1; % Capacitor
x= [0;0;0]; % Initial state vector
Vin= 0.76; % Input
5.2 Animation of Electrical Systems

Vout= x(2)/C2; % Output

buf= [t Vout];
for i= 1:loop
x= RK4(@fun,t,x,Vin,h);
t= t+h;
Vout= x(2)/C2;
buf= [buf;t Vout];
end
plot(buf(:,1),buf(:,2),'linewidth',2)
axis([0 h*loop 0 1])
xlabel('t[sec]'), ylabel('y(t)[V]');
5.2 Animation of Electrical Systems
% RLC Circuit
function xdot= fun(t,x,u)
global C2
R= 1; L= 1; C1= 1;
xdot= zeros(3,1);
xdot(1)= -x(1)/R/C1+x(2)/R/C1+u/R;
xdot(2)= x(3);
xdot(3)= x(1)/L/C1-(1/C1+1/C2)*x(2)/L;
5.2 Animation of Electrical Systems

x(0)= [0 0 0]T, u(t)= 0.76[V] t0


5.2 Animation of Electrical Systems
(2) Animate the change in output voltage when the
input voltage is applied to the RLC circuit for 20[sec].
Program: Example5_3
function Example5_3_2
clf
global C2
t= 0; h= 0.02; loop= 1000; C2= 1; % Capacitor C2
x= [0;0;0]; % Initial state vector
Vin= 0.76; % Input
hold on
% Circuit lines
plot([-1.3 -0.8 inf -0.2 0.1 inf 0.9 1.5],...
[1.5 1.5 1.5 1.5 1.5 1.5 1.5 1.5],'k') % Upper line
plot([-1.3 1.5],[0 0],'k') % Lower line
5.2 Animation of Electrical Systems
% Resistor
[xs,ys]= HResistor(-0.8,1.5,0.6,0.1,5);
plot(xs,ys,'LineWidth',2) % Draw R
text(-0.7,1.8,'R')
% Inductor
[xv,yv]= HCoil(0.1,1.5,0.8,0.1,5);
plot(xv,yv,'LineWidth',2) % Draw L
text(0.45,1.8,'L')
% Capacitor C1 and connection line
[xv,yv]= VCapacitor(0,0.6,0.5,0.2,0.2);
plot(xv,yv,'LineWidth',2) % Draw C1
plot([0 0 0 0 0],[1.5 0.8 inf 0.6 0],'k') % Draw line
text(-0.6,0.7,'C_1')
5.2 Animation of Electrical Systems
% Capacitor C2 and connection line
[xv,yv]= VCapacitor(1,0.6,0.5,0.2,0.2);
plot(xv,yv,'LineWidth',2) % Draw C2
plot([1 1 1 1 1],[1.5 0.8 inf 0.6 0],'k') % Draw line
text(0.45,0.7,'C_2')
% Input voltage
rectangle('Position',[-2 0 0.4 1.5]) % Outer
rectangle('Position',[-2 0 0.4 Vin],'FaceColor','g') %Inner
text(-3.3,0.7,['Vin= ',Mynum2str(Vin)]) % Draw value
% Output voltage
rectangle('Position',[2 0 0.4 1.5]) % Outer
gh1= rectangle('Position',[2 0 0.4 eps],'FaceColor','g'); % Inner
gh2= text(2.6,0.7,'Vout= '); % Get handle gh2
5.2 Animation of Electrical Systems
axis([-3.5 4 -1 3])
hold off

for i= 1:loop
x= RK4(@fun,t,x,Vin,h);
t= t+h;
Vout= x(2)/C2;
set(gh1,'Position',[2 0 0.4 Vout]) % Update gh1
set(gh2,'String',['Vout= ',Mynum2str(Vout)]) % Update gh2
drawnow
pause(0.01)
end
5.2 Animation of Electrical Systems
% RLC circuit
function xdot= fun(t,x,u)
global C2
R= 1; L= 1; C1= 1;
xdot= zeros(3,1);
xdot(1)= -x(1)/R/C1+x(2)/R/C1+u/R;
xdot(2)= x(3);
xdot(3)= x(1)/L/C1-(1/C1+1/C2)*x(2)/L;

% Horizontal resistor
function [x,y]= HResistor(x0,y0,L,r,N)
t= 0:4*N;
x= x0+L*t/(4*N);
y= y0+r*sin(pi*t/2);
5.2 Animation of Electrical Systems
% Horizontal coil
function [x,y]= HCoil(x0,y0,L,r,N)
t= [0:pi/50:(2*N-1)*pi]+3*pi/2;
xv= linspace(0,1,numel(t))+(sin(t)+1)/(2*N);
x= x0+L*xv/max(xv); y= y0+r*cos(t);
% Vertical capacitor
function [x,y]= VCapacitor(x0,y0,wt,ht,q)
if q < 0, q= 0;
elseif q > 1, q= 1;
end
xv= linspace(-wt/2,wt/2,50);
yv= ht-q*ht*sqrt(1-xv.^2/(wt/2)^2);
x= x0+[-wt/2 wt/2 inf xv]; y= y0+[0 0 inf yv];
5.2 Animation of Electrical Systems
% Mynum2str converts the number into a string
function str= Mynum2str(num)
numr= round(num*100)/100;
str= num2str(numr);
5.2 Animation of Electrical Systems

x(0)= [0 0 0]T, u(t)= 0.76[V] t0


5.2 Animation of Electrical Systems
Example 5.4 Consider a PID control system that
controls the rotation angle of an armature-controlled DC
motor. u(t) is the voltage applied to the armature circuit
as input, and (t) is the rotation angle as output.
Plant(DC motor):
R L ef(t)= const J= 0.01[kg.m2]
B= 0.1[N.m.sec/rad]
i(t) Ke= 0.01[V.sec/rad]
u(t) eb(t) (t),(t)
Kt= 0.01[N.m/Amp]
J R= 1[]
B L= 0.5[H]
5.2 Animation of Electrical Systems

Defining the state variables as x1(t)= (t), x2(t)= (t),


x3(t)= i(t) gives the following equations:
  J= 0.01[kg.m2]
0 1 0   
B= 0.1[N.m.sec/rad]
 x1     x1   0  Ke= 0.01[V.sec/rad]
 x   0 B Kt     
 2  -  x2    0  u Kt= 0.01[N.m/Amp]
J J 
 x3     x3   1  R= 1[]
0 Kb R   L= 0.5[H]
- - L
 L 
L
 x1 
y  1 0 0  x2 
 x3 
5.2 Animation of Electrical Systems
PID controller:

The standard PID controller is given by


de(t )
u (t )  K p e(t )  K i  e(t )dt  K d
dt

where e(t)= r(t)-(t), r(t)= /4[rad] t0, Kp= 18, Ki=


7, and Kd= 8.

(1) Plot the angle for 20[sec]


where x(0)= 0 and h= 0.02 [sec].
5.2 Animation of Electrical Systems
Program: Example5_4
function Example5_4_1
clf
x= [0;0;0]; % Initial state vector
r= pi/4; % Set-point
t= 0; h= 0.02; loop= 1000; z= 0; ee= r-x(1);

buf= [t x(1)];
for i= 1:loop
e= r-x(1);
z= z+0.5*h*(e+ee); % Integral of e(t)
ce= (e-ee)/h; % Derivative of e(t)
ee= e; % Update ee
u= 18*e+7*z+8*ce; % PID control
5.2 Animation of Electrical Systems
x= RK4(@fun,t,x,u,h);
t= t+h;
buf= [buf;t x(1)];
end
plot(buf(:,1),180/pi*buf(:,2),'k','linewidth',2); % Draw the angle
axis([0 h*loop 0 80])
xlabel('t[sec]'), ylabel('\theta(t)')
% DC Motor
function xdot= fun(t,x,u)
J= 0.01; B= 0.1; Kb= 0.01; Kt= 0.01; R= 1; L= 0.5;
xdot= zeros(3,1);
xdot(1)= x(2);
xdot(2)= -B*x(2)/J+Kt*x(3)/J;
xdot(3)= -Kb*x(2)/L-R*x(3)/L+u/L;
5.2 Animation of Electrical Systems

x0= [0 0 0]T, r(t)= /4[rad] t0


5.2 Animation of Electrical Systems
(2) Animate the angle control system for 20[sec].
Program: Example5_4
function Example5_4_2
clf
x= [0;0;0]; % Initial state vector
r= pi/4; % Set-point
D= 1; d= 0.1; Dd= D-d; % Radius
t= 0; h= 0.02; loop= 1000; z= 0; ee= r-x(1);

hold on
fill([1.1 1.3 1.3 1.1],[0 -0.1 0.1 0],'r');% Draw the symbol
[xv,yv]= Circle(0,0,D); fill(xv,yv,'b'); % Draw the main disc
5.2 Animation of Electrical Systems

[xv,yv]= Circle(0,0,d/2); fill(xv,yv,'w'); % Draw the center hole


[xv,yv]= Circle(Dd,0,d); gh1= fill(xv,yv,'w'); % Draw the white spot
[xv,yv]= Circle(0,Dd,d); gh2= fill(xv,yv,'g'); % Draw the blue spot
[xv,yv]= Circle(-Dd,0,d); gh3= fill(xv,yv,'g'); % Draw the blue spot
[xv,yv]= Circle(0,-Dd,d); gh4= fill(xv,yv,'g'); % Draw the blue spot
axis equal
axis([-2 2 -2 2]);
hold off

for i= 1:loop
e= r-x(1);
z= z+0.5*h*(e+ee); % Integral of e(t)
ce= (e-ee)/h; % Derivative of e(t)
ee= e; % Update ee
5.2 Animation of Electrical Systems
u= 18*e+7*z+8*ce; % PID control
x= RK4(@fun,t,x,u,h);
t= t+h;
x0= Dd*cos(x(1)); y0= Dd*sin(x(1));
[xv,yv]= Circle(x0,y0,d);
set(gh1,'XData',xv,'YData',yv) % Update gh1 with new xv and yv
x0= Dd*cos(pi/2+x(1)); y0= Dd*sin(pi/2+x(1));
[xv,yv]= Circle(x0,y0,d);
set(gh2,'XData',xv,'YData',yv) % Update gh2 with new xv and yv
x0= Dd*cos(pi+x(1)); y0= Dd*sin(pi+x(1));
[xv,yv]= Circle(x0,y0,d);
set(gh3,'XData',xv,'YData',yv) % Update gh3 with new xv and yv
x0= Dd*cos(1.5*pi+x(1)); y0= Dd*sin(1.5*pi+x(1));
[xv,yv]= Circle(x0,y0,d);
5.2 Animation of Electrical Systems
set(gh4,'XData',xv,'YData',yv) % Update gh4 with new xv and yv
drawnow, pause(0.01)
end

% DC Motor
function xdot= fun(t,x,u)
J= 0.01; B= 0.1; Kb= 0.01; Kt= 0.01; R= 1; L= 0.5;
xdot= zeros(3,1);
xdot(1)= x(2);
xdot(2)= -B*x(2)/J+Kt*x(3)/J;
xdot(3)= -Kb*x(2)/L-R*x(3)/L+u/L;
5.2 Animation of Electrical Systems

x0= [0 0 0]T, r(t)= /4[rad] t0


5.3 Animation of Hydraulic Systems
Example 5.5 Consider a system that controls the level
of an 1-tank system. When the input flow rate qi(t)
changes in the equilibrium state, the tank level h(t) and
the output flow rate qo(t) also change. Applying the
equilibrium equation of the fluid gives the following
equation:
Plant(Water tank):
dh(t ) S= 0.3[m2]
S  qi (t )  qo (t )
dt A= 0.003[m2]
qo (t )  A 2 gh(t ) g= 9.8[m/sec2]
5.3 Animation of Hydraulic Systems
PI controller:

The standard PI controller is given by


u (t )  K p e(t )  K i e(t ) dt

where e(t)= r(t)-h(t), r(t)= 0.8[m] t0, Kp= 5, and Ki=


3.

(1) Plot the level for 5[sec] with h(0)= 0.2[m] and ts=
0.02 [sec].
5.3 Animation of Hydraulic Systems
Program: Example5_5
function Example5_5_1
clf
t= 0; ts= 0.01; z= 0; loop= 200; Kp= 5; Ki= 0.1;
x= 0.2; % Initial state
r= 0.8; % Set-point
buf= [t x];
for i= 1:loop
e= r-x; z= z+ts*e; % Integral of e(t)
if e >= 0
u= Kp*e+Ki*z; % PI control
else
u= 0; % No control when e(t) < 0
end
5.3 Animation of Hydraulic Systems
x= RK4(@fun,t,x,u,ts);
t= t+ts;
buf= [buf;t x];
end
plot(buf(:,1),buf(:,2),'k','linewidth',2); % Draw the level
axis([0 ts*loop 0 1.2])
xlabel('t[sec]'), ylabel('h(t)')

% One-tank
function xdot= fun(t,x,qi)
S= 0.3; A= 0.003; g= 9.8;
xdot= (qi-A*sqrt(2*g*x))/S;
5.3 Animation of Hydraulic Systems

x(0)= 0.2[m], r(t)= 0.8[m] t0


5.3 Animation of Hydraulic Systems
(2) Animate the level control system for 2[sec].
Program: Example5_5
function Example5_5_2
clf
t= 0; ts= 0.01; z= 0; loop= 200; Kp= 5; Ki= 0.1;
x= 0.2; % Initial state
r= 0.8; % Set-point
hold on
plot([0.7 1 2 2.3],[-0.5 -0.03 -0.03 -0.5],'k','LineWidth',2);%
Draw the base
plot([1 1 2 2],[1.5 0 0 1.5],'k','LineWidth',2);% Draw the tank
plot([2 2.3],[0 0],'b','LineWidth',2);% Draw outlet pipe
plot([2.4 2.3 2.4 2.3 2.4],[-0.1 0 0 0 0.1],'g');% Draw outlet water
5.3 Animation of Hydraulic Systems
plot([0.5 1.2 1.2],[1.6 1.6 1.4],'b','LineWidth',2);% Draw inlet pipe
plot([1.1 1.2 1.2 1.2 1.3],[1.3 1.4 1.3 1.4 1.3],'g');% Draw inlet water
fill([2 2.1 2.1 2],[r r-0.07 r+0.07 r],'r');% Draw set-point mark
text(2.2, r, ['r= ',Mynum2str(r)]); % Draw set-point value

gh1= fill([1.01 1.01 1.99 1.99 1.01],[x 0 0 x x],'g'); % Draw water level
gh2= text(0.5,1.7,'u= 0'); % Draw inlet flow rate
axis([0 3 -0.5 2])
title('Level control of an one-tank')
hold off

for i= 1:loop
e= r-x;
z= z+ts*e; % Integral of e(t)
5.3 Animation of Hydraulic Systems
if e >= 0
u= Kp*e+Ki*z; % PI control
else
u= 0; % No control when e(t) < 0
end
x= RK4(@fun,t,x,u,ts); t= t+ts;
set(gh1,'YData',[x 0 0 x x]) % Update gh1
set(gh2,'String',['u= ',Mynum2str(u)]); % Update gh2
drawnow, pause(0.1);
end
% One-tank
function xdot= fun(t,x,qi)
S= 0.3; A= 0.003; g= 9.8;
xdot= (qi-A*sqrt(2*g*x))/S;
5.3 Animation of Hydraulic Systems

x(0)= 0.2[m], r(t)= 0.8[m] t0


5.4 Animation of a Model Car System
Example 5.6 A model car is represented by the
following formula where x1(k) and x2(k) are the
horizontal and vertical positions of the rear of the model
car, x3(k) is the angle of the model car from the
horizontal axis, u(k) is the steering angle, v is the speed,
and  is the length of the model car, and h is the
sampling time.
Plant(Model car):
x1 (k  1)  x1 ( k )  vh cos( x3 ( k )) v= 1[m/sec]
x2 (k  1)  x2 (k )  vh sin( x3 (k )) = 4[m]
vh h= 1[sec]
x3 (k  1)  x3 (k )  tan(u ( k ))

5.4 Animation of a Model Car System
Fuzzy controller:
The Takagi-Sugeno type fuzzy control rules for
trajectory control and the membership function of the
fuzzy sets used are as follows:
R1: If x3(k) is about 0, then u1(k)= f11x2(k)+f12x3(k)
R2: If x3(k) is about , then u2(k)= f21x2(k)+f22x3(k)
R3: If x3(k) is about -, then u3(k)= f21x2(k)+f22x3(k)
where f11= -0.4212, f12= -0.02933, f21= -0.0991, f22= -0.00967
5.4 Animation of a Model Car System
If with an input= x3(k), the firing strength of each
rule is i, the final output of the system is the
weighted average of all rule outputs, computed as
n n
u (k )  
i 1
 i u i (k ) / 
i 1
i

where n is the number of rules(= 3).

(1) Plot the trajectory x3(k) of the system for 350[sec]


with x(0)= [30 40 -20]T and h= 1[sec].
5.4 Animation of a Model Car System
Program: Example5_6
function Example5_6_1
clf
x= [30; 40; -20*pi/180]; % Initial state vector
b= [0 x(1) x(2)];
for k= 1:350
a1= trimf(x(3), [-pi -pi 0]); % Firing strength of 'about -pi'
a2= trimf(x(3), [-pi 0 pi]); % Firing strength of 'about 0'
a3= trimf(x(3), [0 pi pi]); % Firing strength of 'about pi'
u1= [-0.4212 -0.02933]*[x(3) x(2)]'; % Control input 1
u2= [-0.0991 -0.00967]*[x(3) x(2)]'; % Control input 2
u3= [-0.0991 -0.00967]*[x(3) x(2)]'; % Control input 3
u= (a1*u1+a2*u2+a3*u3)/(a1+a2+a3); % Final control input
x= ModelCar(x,u); % Get the new state
5.4 Animation of a Model Car System

b= [b; k x(1) x(2)];


end
plot(b(:,1), b(:,2),'k',b(:,1), b(:,3),'r') % Draw the trajectory
axis([0 350 -100 350]);
xlabel('x_1(k)'); ylabel('x_2(k)');
legend('x_1(k)','x_2(k)','location','northwest')

% Implement the model car


function newx= ModelCar(x,u)
v= 1; h= 1; L= 4;
newx= zeros(3,1);
newx(1)= x(1)+v*h*cos(x(3));
newx(2)= x(2)+v*h*sin(x(3));
newx(3)= x(3)+v*h*tan(u)/L;
5.4 Animation of a Model Car System

x(0)= [30 40 - 20]T, x3(k) = 0 k0


5.4 Animation of a Model Car System
(2) Animate the model car control system for 350[sec].
Program: Example5_6
function Example5_6_2
clf
x= [30; 40; -20*pi/180]; % Initial state vector
wt= 20; ht= 20; % Model car dimension
hold on
plot(x(1), x(2),'bo') % Draw the intial position
gh1= plot(x(1), x(2),'r'); % Draw the trajectory
[xv,yv]= DrawCar([x(1) x(2) wt ht],x(3));
gh2= fill(xv,yv,'g'); % Draw the model car
axis equal
axis([0 400 -150 150]);
5.4 Animation of a Model Car System
xlabel('x_1(k)'); ylabel('x_2(k)');
title('Fuzzy Trajectory Control of a Model Car');
grid on
hold off

b= [];
for k= 1:350
a1= trimf(x(3), [-pi -pi 0]); % Firing strength of 'about -pi'
a2= trimf(x(3), [-pi 0 pi]); % Firing strength of 'about 0'
a3= trimf(x(3), [0 pi pi]); % Firing strength of 'about pi'
u1= [-0.4212 -0.02933]*[x(3) x(2)]'; % Control input 1
u2= [-0.0991 -0.00967]*[x(3) x(2)]'; % Control input 2
u3= [-0.0991 -0.00967]*[x(3) x(2)]'; % Control input 3
u= (a1*u1+a2*u2+a3*u3)/(a1+a2+a3); % Final control input
5.4 Animation of a Model Car System
x= ModelCar(x,u); % Get the new state
b= [b; x(1) x(2)];
set(gh1,'XData',b(:,1),'YData',b(:,2)) % Update gh1
[xv,yv]= DrawCar([x(1) x(2) wt ht],x(3));
set(gh2,'XData',xv,'YData',yv) % Update gh2
drawnow, pause(0.03);
end
% Implement the model car
function newx= ModelCar(x,u)
v= 1; h= 1; L= 4;
newx= zeros(3,1);
newx(1)= x(1)+v*h*cos(x(3));
newx(2)= x(2)+v*h*sin(x(3));
newx(3)= x(3)+v*h*tan(u)/L;
5.4 Animation of a Model Car System
% Generate data for drawing the car
function [xv,yv]= DrawCar(para,ang)
x0= para(1); y0= para(2); w= para(3); h= para(4);
xv = [w/2 w/2 w w/2 -w/2 -w/2 w/2];
yv = [-h/2 h/2 0 -h/2 -h/2 h/2 h/2];
[xv yv]= MatrixRotation(xv,yv,ang);
xv= x0+xv;
yv= y0+yv;

function [x,y]= MatrixRotation(x0,y0,ang)


x= cos(ang)*x0-sin(ang)*y0;
y= sin(ang)*x0+cos(ang)*y0;
5.4 Animation of a Model Car System

x(0)= [30 40 - 20]T, x3(k) = 0 k0


Lecture-6: Genetic Algorithms

 Handle graphics and graphic objects


 Handles and property changes
 Commands for Animation
 Examples of simple animation
6.1 What are EAs ?
 Evolutionary algorithms (EAs) are a family of
population-based problem solvers with a
metaheuristic or stochastic character.
 In evolutionary computation, an initial set of
candidate solutions is generated and iteratively
updated. Each new generation is produced by
stochastically removing less desired solutions,
and introducing small random changes.
 The iteration sequence is continued until a
termination criterion is met.
6.1 What are EAs ?
 Ant colony optimization (ACO) is a
probabilistic algorithm for solving
computational problems inspired by the
pheromone-based communication behavior
of real ants (M. Dorigo, 1992).
 Evolution strategies (ESs) use natural
problem-dependent representations, and
primarily mutation and selection, as search
operators(I. Rechenberg, H. Schwefel et al.,
1970s).
6.1 What are EAs ?
 Particle swarm optimization (PSO) is a
computational method that improves a
candidate solution with regard to a given
measure of quality. It is based on the ideas of
animal flocking behavior (Kennedy, Eberhart
and Shi, 1995).
 Simulated annealing (SA) is a probabilistic
technique for approximating the global
optimum of a given function.
6.1 What are EAs ?
 The name and inspiration come from
annealing in metallurgy, a technique
involving heating and controlled cooling of a
material to increase the size of its crystals
and reduce their defects. (Kirkpatrick, Gelatt
Jr.,Vecchi, 1983).
 Genetic algorithm (GA) is the most popular
type of EA(J. Holland, 1975).
6.1 What are EAs ?
Goldbergs view on EAs
Performance of methods

Evolutionary Problem-tailored
algorithms methods

Random
search

Range of problems
6.2 What are GAs ?
A global search algorithm based on
 Natural evolution- the fittest
individuals survive
 Genetics- organisms produce
offspring via sexual mating
 Natural mutation-
sometime benefit for
organisms
 Developed: J. Holland
in the 1975
6.2 What are GAs ?
Basic structure of GA
k= 0;
Compute an initial population P(0);
Evaluate the fitness;
WHILE <stopping condition not fulfilled> DO
BEGIN
k= k+1;
Select individuals for reproduction;
Create offspring by crossover;
Mutate some individuals;
Evaluate the fitness;
END
6.2 What are GAs ?
Start

Initialize Fitness
population evaluation

yes
Converged ?
Population no
(1100010110) Selection Output
results
(0110100101)
(1110101110) Crossover
(1010010111) Stop
(0011010111)
(1010011100) Mutation
6.2 What are GAs ?
Some features of GAs
Compared with traditional optimization
methods, such as gradient descent methods,
GAs have the following significant differences:

1. Use of a coding (except RCGAs)


manipulate coded versions of decision
variables instead of the parameters
themselves.
6.2 What are GAs ?
2. Search from a population, not a single point
 While almost all conventional methods
search from a single point, GAs always
operate on a population of points (strings).
 This contributes much to the robustness of
genetic algorithms. It improves the chance of
reaching the global optimum and, vice versa,
reduces the risk of becoming trapped in a
local stationary point.
6.2 What are GAs ?
3. Use of only payoff information
Normal genetic algorithms do not use any
other information except payoff (objective
function) such as derivatives.
Therefore, they can be applied to any kind of
continuous or discrete optimization problem.
The only thing to be done is to specify a
meaningful decoding function.
6.2 What are GAs ?
4. Stochastic search
GAs use probabilistic transition operators
while conventional methods apply
deterministic transition operators to guide a
highly global search .
More specifically, the way a new generation is
computed from the actual one has some
random components.
6.2 What are GAs ?
Differences between two methods
Traditional Methods Evolutionary Methods
Single solution A set of potential
solutions (population)
Derivative of the Some mechanism for
objective function searching and escaping
local optima
Local optima Global optima
Deterministic results Stochastic results
6.3 GA: Chromosome
Cell and chromosome
 A human cell contains 23 pairs of
chromosomes made of protein and DNA.
 DNA, passed from parents to offspring,
contains the specific instructions that make
each human unique.
6.3 GA: Chromosome
Chromosome representation
 Encoding represents solutions to the problem
as a chromosome, i.e. a sequence of genes from
a predefined alphabet.
 There are three encoding methods: binary, real
number, symbolic.
6.3 GA: Chromosome
1. Binary encoding
 Every chromosome is a string of bits, 0 or 1.
 The string length  determines possible
maximum precision of solution.
 High precision needs long chromosome but
introduces slow evolution (computational
burden).
x= [0.2 -0.4 0.7]T
s= (101001001111)
x1 x2 x3
6.3 GA: Chromosome
Mapping real values on bit strings
Given a string length of  , a real value can be
represented by a binary string as.
Step 1. Map the variable x linearly to an
unsigned integer u between [0, 2 1 ]. The equation
shows the relationship between them.
2 1
u  fix[ ( x  x ( L ) )]
x (U )  x ( L )
Step 2. Convert u to a binary string. Combine
converted strings for multi-variables.
6.3 GA: Chromosome
Example 1: Convert x= [3.5 0]T to a string
where each substring has a length of 5 and -5
x1, x2 5.
21 1 31
u1  ( x1  x1( L ) )   (3.5  5)  26
x1(u )  x1( L ) 10
 2 1
2 31
u2  ( x2  x2( L ) )   (0  5)  15
x2(u )  x2( L ) 10

Since 26 → 11010 and 15 → 01111, we have


s= (11010 00111)
6.3 GA: Chromosome
Disadvantages of binary encoding
• Increasing the precision of the solution requires
the longer length of the chromosome. This may
be a computational burden.
• This encoding is often not natural for many
problems and can introduce the hamming cliff
problem.
• A Hamming cliff is formed when two
numerically adjacent values have bit
representations that are far apart.
6.3 GA: Chromosome
• For example
x1= 15, s= (01111)
Binary Gray
x2= 16, s= (10000)
Hamming distance= 5

• Gray encoding ensures


that consecutive integers
always have Hamming
distance one.
6.3 GA: Chromosome
2. Real number encoding
 Real number encoding is as same as used in x
and is very good for some special problems.
 This encoding is often necessary to develop
some new crossover and mutation specific for
the problem.
x= [0.2 -0.4 0.7]T
s= (0.2, -0.4, 0.7)
x1 x2 x3
6.3 GA: Chromosome
3. Symbolic encoding (permutation encoding)
 Every chromosome is a string of numbers,
which represents number in a sequence.
Job A
1
s= (1, 3, 4, 2, 5)
Job E 5 2
Job B
A C D B E
4 3
Job D Job C
6.3 GA: Chromosome
 Permutation encoding is only useful for
ordering problems, such as travelling
salesman problem, time tabling problem or
task ordering problem.
 Even for this problems for some types of
crossover and mutation corrections must be
made to keep the chromosome consistent
6.3 GA: Population Initialization
Start

Initialize Fitness
population evaluation

yes
Converged ?
Population no
(1100010110) Selection Output
results
(0110100101)
(1110101110) Crossover
(1010010111) Stop
(0011010111)
(1010011100) Mutation
6.3 GA: Population Initialization
Start

Initialize Fitness
population evaluation

yes
Converged ?
Population no
(4.3,2.1,0.5) Selection Output
results
(0.1,3.3,1.1)
(6.2,9.1,0.6) Crossover
(3.5,6.6,8.1) Stop
(6.2,7.2,3.2)
(4.2,5.5,8.0) Mutation
6.3 GA: Population Initialization
Start

Initialize Fitness
population evaluation

yes
Converged ?
Population no
(42637185) Selection Output
results
(46231578)
(24315678) Crossover
(45826317) Stop
(36247851)
(27364815) Mutation
6.3 GA: Population Initialization
The initial population P(0) can be generated
randomly or heuristically.

1. Random method
 choose gene values randomly from the
allowed set of values. A random number
generator is used.
 ensure that P(0) is a uniform representation
of the entire search space.
 use this method for research to test a new
GA performance.
6.3 GA: Population Initialization
2. Heuristic method
 use this method to bias P(0) toward good
solutions when prior knowledge about the
search space is available
 use to solve real optimization problems

Random method Heuristic method


6.3 GA: Population Initialization
Example 2: Generates P(0) with three gains Kp,
Ki, and Kd as chromosomes randomly, where the
population size is 6 and 0  Kp, Ki, Kd  10.
Kp Ki Kd
4.3 2.1 0.5 Gene
0.1 3.3 1.1
Population 6.2 9.1 0.6
Chromosome
P(0) 3.5 6.6 8.1
(Individual,
6.2 7.2 3.2
Structure)
4.2 5.5 8.0
6.3 GA: Population Initialization
popsize= 6; LB= [0 0 0]; UB= [10 10 10];
for i= 1:popsize
pop(i,:)= LB+(UB-LB).*rand(1,3);
end
pop
pop =
2.8101 4.4009 5.2714
4.5742 8.7537 5.1805
9.4362 6.3771 9.5769
2.4071 6.7612 2.8906
6.7181 6.9514 0.6799
2.5479 2.2404 6.6783
6.3 GA: Population Initialization
• The size of the initial population P(0) has
consequences for performance in terms of
accuracy and the time to converge.
• A small population represents a small part of
the search space; the time per generation is
low, need more generations to converge.
• A large population size covers a larger area of
the search space; require less generations to
converge. However, the time per generation is
increased.
6.3 GA: Fitness Evaluation
 Decides how ‘good’ the solution is with respect
to the problem. Fitness function is used to guide
simulation towards the optimal solution.
 Fitness F is calculated from the objective
function f(x)
 Maximization problem: Max f(x)
F= f(x) +c1  0
 Minimization problem : Min f(x)
F = - f(x) +c2  0 or F = 1/[f(x) +c3]  0
6.3 GA: Fitness Evaluation
Example 3: Min f(x)= 0.15(x-1)2-1
4 6 12

2 4 8

0 2 4

-2 0 0
-2 0 2 4 6 -2 0 2 4 6 -2 0 2 4 6
a) f(x) b) F= -f(x)+c2 c) F= 1/[f(x)+c3]
c2= 2.75 c3= 1.1
6.3 GA: Fitness Evaluation

Example 5: Min f   | r  y | dt
0

P(0) Fitness
(4.3, 2.1, 0.5) 14.0
(0.1, 3.3, 1.1) 2.3
(6.2, 9.1, 0.6) 16.2
(3.5, 6.6, 8.1) 5.4
(6.2, 7.2, 3.2) 6.3
(4.2, 5.5, 8.0) 0.9
6.3 GA: Selection
 Mimics the natural selection. Better individuals
get higher chance for survival
 Chances are proportional to fitness
 The most frequently used selection operators:
- Roulette wheel(Assign to each individual a part
of the roulette wheel. Commonly used method)
- Tournament
- Remainder stochastic sample with replacement
- Ranking-based
- Affine (Prof. Jin proposed)
6.3 GA: Selection
a. Roulette wheel selection
 The fittest individuals have a greater chance of
survival than weaker ones.
 Assign to each individual a part of the roulette
wheel.
 The number of times the roulette wheel is spun
is equal to size of the population.
 Commonly used method
6.3 GA: Selection
6.3 GA: Selection
P(0) Fitness Psel Roulette
 (4.3, 2.1, 0.5) 14.0 31% wheel method
 (0.1, 3.3, 1.1) 2.3 5%
 (6.2, 9.1, 0.6) 16.2 36%
 (3.5, 6.6, 8.1) 5.4 12% P(1)
 (6.2, 7.2, 3.2) 6.3 14%  (4.3, 2.1, 0.5)
 (4.2, 5.5, 8.0) 0.9 2%  (6.2, 7.2, 3.2)
45.0 100%  (6.2, 9.1, 0.6)
 (3.5, 6.6, 8.1)
 (6.2, 9.1, 0.6)
 

 (4.3, 2.1, 0.5)
Selection
position  
6.3 GA: Selection
b. Tournament selection
 Runs several tournaments among a few
individuals chosen at random.
 The winner of each tournament (the one with
the best fitness) is selected for crossover.
6.3 GA: Selection
c. Ranking-based selection
 The rank selection first ranks the population and
then every chromosome receives fitness from
this ranking.
 The worst will have fitness 1, second-worst 2,
and the best-case will have fitness N (number of
chromosomes in population).
 After this, all the chromosomes have a chance to
be selected.
 Rank-based selection can avoid premature
convergence.
6.3 GA: Selection
d. Affine selection 9

fbest  fi
0

xi (k  1)  xi (k )   [ xb (k )  xi (k )] -9
3

fbest 0
-3 -3
0
3

 Selects individuals
according to their fitness
values.
 The larger the difference,
the larger the movement
toward the best.
6.3 GA: Selection
 By collecting weak
individuals discarded by
the R/W method toward
the best, it increases the
total fitness and increases
genetic diversity.
 Be used only with real
number encoding
chromosomes.
6.3 GA: Crossover
 Imitates sexual reproduction
in nature
 Produces offspring from
two parents to exchange
information between
chromosomes
 Crossover takes place with a
probability Pc[0, 1].
 There are various operators depending on the
chromosome encoding
6.3 GA: Crossover
6.3 GA: Crossover
Binary encoding
a. One point xover
Xover point
s1= (0011011) s1= (0001100)
s2= (1101100) s2= (1111011)
b. Two point xover
s1= (0011011) s1= (0011101)
s2= (1101100) s2= (1101010)
Xover points
6.3 GA: Crossover
c. Uniform xover
 The mask of the same length is created at
random for each pair of individuals selected.
 A bit with value of 1 indicates that the
corresponding alleles have to be swapped
between the two parents.
s1= (0011011) s1= (1011100)
s2= (1101100) s2= (0101011)
Mask= (1000111)
6.3 GA: Crossover
Real number encoding
a. Simple xover
Xover point
s1= (-2.3, 4.5, 7.4) s1= (-2.3, 6.6, -0.5)
s2= (1.6, 6.6, -0.5) s2= (1.6, 4.5, 7.4)
b. Flat xover
-selects two parents and generate one child such
that it assign random real number in child gene
which is either min or max from genes in both
parents.
6.3 GA: Crossover

s1= (-2.3, 4.5, 7.4) s1= (1.5, 5.2, 6.4)


s2= (1.6, 6.6, -0.5)

c. Arithmetic xover
- Two parents produce two offspring. The
offspring are arithmetically produced by the
following equation (Kaelo and Ali, 2007):
6.3 GA: Crossover

x= (x1, x2, x3) x= (x1, x2, x3)


y= (y1, y2, y3) y= (y1, y2, y3)
Parents Offspring

xi= yi+(1-) xi
yi= xi+(1-)yi
where [0,1) is a uniform random number and
may vary with regard to chromosome.
6.3 GA: Crossover
Example 6: Produce the offspring arithmetically
with given two parents where = 0.23.
x= (2.3, -4.1, 7.4), y= (-1.8, 5.9, 3.2)

Solution:

x’= (1.357, -1.800, 6.434),


y’= (-0.857, 3.600, 4.166)
6.3 GA: Crossover
Symbolic encoding
a. Partially-mapped xover (PMX)
 It transmits ordering and values information
from the parents to the offspring.
 The PMX operator creates an offspring in the
following way.
Step 1. Select two cut points random.
s1= (1 2 3 4 5 6 7 8)
s2 = (3 7 5 1 6 8 2 4)
Step 2. Exchange the substrings(the mapping
sections) between the cut points.
6.3 GA: Crossover
s1= (   1 6 8  )
s2 = (   4 5 6  )
Step 3. Define the mappings
41
5  6 and 6  8

Step 4. The other elements in the offspring are


filled up by mappings.
s1= (4 2 3 1 6 8 7 6)
s2 = (3 7 6 4 5 6 2 1)
6.3 GA: Crossover
b. Order xover (OX)
 It constructs an offspring by choosing a
substring of one parent and preserving the
relative order of the elements of the other.
 The OX operator creates an offspring in the
following way.
Step 1. Select two cut points random.
s1= (1 6 3 4 5 7 2 8)
s2 = (2 4 6 8 7 5 3 1)
Step 2. Exchange the substrings between the cut
points.
6.3 GA: Crossover
s1= (   6 8 7  )
s2 = (   3 4 5  )
Step 3. Next, starting from the second cut point
of one parent, the rest of the elements are copied
in the order in which they appear in the other
parent, also starting from the second cut point
and omitting the elements that are already
present. When the end of the parent string is
reached, we continue from its first position:
5–3–1–2–4–6–8–7 5–3–1–2–4
7–2–8–1–6–3–4–5 7–2–8–1–6
6.3 GA: Crossover

5–3–1–2–4
7–2–8–1–6
s1= (1 2 4 6 8 7 5 3)
s2 = (8 1 6 3 4 5 7 2)
6.3 GA: Crossover
c. Cycle xover (CX)
 It create an offspring from the parents where
every position is occupied by a corresponding
element from one of the parents.
 The CX operator creates an offspring in the
following way.

Step 1. Select two parents.


s1= (4 1 2 6 8 7 3 5)
s2 = (8 6 2 4 5 3 7 1)
6.3 GA: Crossover
s1= (4 1 2 6 8 7 3 5)
s2 = (8 6 2 4 5 3 7 1)
Step 2. Find cycles existing between two parents.
cycle 1: 4 8 5 1 6 4
cycle 2: 8 4 6 1 5 8

Step 3. If the parent's genes are included in their


cycles, they are copied to their offspring.
s1= (4 1  6 8   5)
s2 = (8 6  4 5   1)
6.3 GA: Crossover
s1= (4 1 2 6 8 7 3 5)
s2 = (8 6 2 4 5 3 7 1)

Step 4. The remaining positions are taken from


the other parent except the genes included in the
cycle.
s1= (4 1 2 6 8 3 7 5)
s2 = (8 6 2 4 5 7 2 1)
6.3 GA: Mutation
Mutation is a genetic operator used to maintain
genetic diversity from one generation to the
next.
It mimics natural (biological) mutation.
6.3 GA: Mutation
Mutation alters one or more gene values in a
chromosome from its initial state. In mutation,
the solution may change entirely from the
previous solution. Hence GA can come to a
better solution by using mutation.
Mutation alters each gene independently with a
mutation probability pm.
There are various operators depending on the
chromosome encoding.
6.3 GA: Mutation
Binary encoding
a. Simple mutation
 It selects one or more bits randomly and flip
with 0 changed to 1 and 1 changed to 0, with a
probability given by the mutation rate.

s1= (1 1 0 1 0 0 1 0)

s1= (1 1 0 1 0 1 1 0)
 This is used for binary encoding GA.
6.3 GA: Mutation
6.3 GA: Mutation
Symbolic encoding
a. Swap Mutation
 It selects two positions on the chromosome at
random, and swaps their positions.
 This is common in permutation based
encoding.

s1= (3 2 4 1 5 6 8 7)

s1= (3 2 7 1 5 6 8 4)
6.3 GA: Mutation
b. Scramble Mutation
Picks a subset of genes at random
Randomly rearranges the alleles in those
positions.

s1= (3 2 4 1 5 6 8 7)
s1= (3 1 2 5 4 6 8 7)
6.3 GA: Mutation
c. Inversion Mutation
It select a subset of genes like in scramble
mutation but instead of shuffling the subset,
it merely invert the entire string in the
subset.

s1= (3 2 4 1 5 6 8 7)
s1= (3 2 4 1 8 6 5 7)
6.3 GA: Mutation
d. Insert Mutation
Picks two positions at random
Moves the second to follow the first,
shifting the rest along to make room
Note that this preserves most of the order
and the adjacency information
s1= (3 2 4 1 5 6 8 7)
s1= (3 2 5 4 1 8 6 7)
6.3 GA: Mutation
Real number encoding
a. Uniform mutation
- A gene is randomly selected and its value is
changed with a random value between lower
and upper bounds.
x1 x2 x3 x4
s1= (1.37, -2.04, 0.06, 0.17), -5.0  x3  5.0
s1= (1.37, -2.04, 2.92, 0.17)
6.3 GA: Mutation
b. Boundary mutation
- Boundary mutation is a special form of
uniform mutation.
- A gene is randomly selected and its value is
changed with one of the two bounds, xi(L) or
xi(U), with equal probability.
x1 x2 x3 x4
s1= (1.37, -2.04, 0.06, 0.17), -5.0  x3  5.0
s1= (1.37, -2.04, 5.00, 0.17)
6.3 GA: Mutation
c. Creep mutation
- A gene is randomly selected and its value is
changed with a real value one of the two
bounds, xi(L) or xi(U), with equal probability.
x1 x2 x3 x4
s1= (1.37, -2.04, 0.06, 0.17), -5.0  x3  5.0
s1= (1.37, -2.04, 5.00, 0.17)
6.3 GA: Mutation
d. Non-uniform mutation

 i
x   ( k , x (U )
 xi ) if q  0
x= (x1, x2, x3) '
xi   i
( L)
 i
x   ( k , x i  xi ) if q  1
x= (x1, xi, x3) k
(1 )b
where (k , y )  y[1  r T ]

xi(U), xi(L): upper and lower bounds of xi


q: random digit (0 or 1)
r: uniform random number, r[0,1)
T: maximum generation number
b: parameter (b= 5), k: current generation
6.3 GA: Mutation
Exploration of Non-uniform mutation
6.4 Special Strategy
Elitist strategy
The best individual may be destroyed through
genetic operations in the next generation.
This introduces search stagnation.
The elitist strategy idea is to transfer the best
individual of the current generation to the
next generation.
Ensuring the survival of the elite solution is a
method for improving the GA performance.
6.4 Special Strategy
Start

Initialize Fitness
population evaluation
yes
Converged ?
no
Population
(4.3,2.1,0.5) Selection Output
results
(0.1,3.3,1.1)
(6.2,9.1,0.6) Crossover
(3.5,6.6,8.1) Stop
(6.2,7.2,3.2)
(4.2,5.5,8.0) Mutation
yes Best
Copy the saved destroyed?
best
6.5 Parameter Settings
Population size(N)
 Large N increases genetic diversity at the
expense of requiring more computation
(N= 20-200)
Crossover rate(Pc)
 Controls crossover frequency(Pc= 80-100%)
 Large Pc can destroy good schemata
Mutation rate(Pm)
 Controls mutation frequency(Pm= 0.5-1%)
 Large Pm increases population diversity but
will destroy good schemata
6.6 Searching the space

(1) P(0) (2) P(1)

Solution

(3) P(10) (4) P(20)


Q&A
Lecture-7: Applications of GAs

 Matlab GA function
 Optimization of a user-defined function
 Optimization of a simulink model
7.1 MATLAB GA Function
Multi-variable Constrained Problem
Consider a multi-variable optimization problem:

Minimize f(x)
s.t. Ax  B (linear inequality constraints)
Aeqx = Beq (linear equality constraints)
C(x)  0 (nonlinear inequality constraints)
Ceq(x)= 0 (nonlinear equality constraints)
S= {x x(L)  x  x(U)} (bounds)
7.1 MATLAB GA Function
ga function
x= ga(fun,nvars)
x= ga(fun,nvars,A,b)
x= ga(fun,nvars,A,b,Aeq,beq)
x= ga(fun,nvars,A,b,Aeq,beq,lb,ub)
x= ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon)
x= ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,options)
x= ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon)
x= ga(fun,nvars,A,b,[],[],lb,ub,nonlcon,IntCon,options)

Note that if input arguments are not used, set them


with an empty array [].
7.2 Optimization of User-Defined Function
Example 1:
Minimize f ( x )  x12  x22  x32
s.t. -50  x1, x2, x3  50
Find the solution using the MATLAB ga function.
Solution: Boundary constraint can be rewritten as
 50  50 
LB   50  , UB  50 
 50  50 

x= ga(fun,nvars,A,b,Aeq,beq,lb,ub,nonlcon,options)
7.2 Optimization of User-Defined Function
% MATLAB ga
function example1
options= optimoptions('ga','PlotFcn',@gaplotbestf);
options.PopulationSize= 200;
options.MaxGenerations= 500;
nvar= 3;
LB= -50*ones(n,1);
UB= 50*ones(n,1);
[x,fval]= ga(@fun1,nvar,[],[],[],[],LB,UB,[],options)

function objfunc= fun1(x)


objfunc= sum(x.^2);
7.2 Optimization of User-Defined Function

x = 1.0e-04 * [0.5238 -0.0046]


fval = 2.7435e-09
7.2 Optimization of User-Defined Function
Example 2:
Minimize f ( x )  ( x1  1) 2  x22
s.t. x2  -1
Find the solution using the MATLAB ga function.

Solution: Constraint can be rewritten as


 x1 
0 1  x   1
 2
7.2 Optimization of User-Defined Function

function example2
nvar= 2; A= [0 1]; b= -1;
opts= optimoptions('ga','PlotFcn', @gaplotbestf);
[x,fval]= ga(@fun2,nvar,A,b,[],[],[],[],[],opts)

function fx= fun2(x)


fx= (x(1)-1)^2+x(2)^2;
7.2 Optimization of User-Defined Function

x = 1.0000 -1.0000 fval = 1.0000


7.2 Optimization of User-Defined Function
Example 3. Tune the PID gains in terms of
minimizing the objective function:

r+ e 1 u e 3s y
Kp+Ki +Kds
- s 10 s  1
Gc(s) Gp(s)

Min f ( K p , K i , K d )  
0
| r  y | dt

s.t. Y(s)/R(s)= Gc(s)Gp(s)/[1+Gc(s)Gp(s)]


S={(Kp,Ki,Kd)|0  Kp,Ki,Kd  5}
7.2 Optimization of User-Defined Function
function example3
nvar= 3;
opts= optimoptions('ga','PlotFcn', @gaplotbestf);
LB= [0;0;0];
UB= [15;15;15];
[x,fval]= ga(@EvalObj,nvar,[],[],[],[],LB,UB,[],opts)
7.2 Optimization of User-Defined Function
function objfunc= EvalObj(pop)
popsize= size(pop,1);
objfunc= zeros(popsize,1);
for k= 1:popsize
Kp= pop(k,1); Ki= pop(k,2); Kd= pop(k,3);
% Parameter settings
t= 0; h= 0.01; x= 0; yr= 1; ee= yr-x; z= 0;
id= 1; L= 3; loop= 4000;
SetTimeDelay(id,L,h); % set time delay
objfunc(k)= 0;
7.2 Optimization of User-Defined Function
for i= 1:loop
e= yr-x; % Calculates the error
% Calculates the IAE performance
se= abs(e);
if i==1 || i==loop
objfunc(k)= objfunc(k)+0.5*h*se;
else
objfunc(k)= objfunc(k)+h*se;
end
if objfunc(k) > 1e+10
objfunc(k)= 1e+10; break;
end
7.2 Optimization of User-Defined Function
z= z+0.5*h*(e+ee); % Computes the integral
ce= (e-ee)/h; % Computes the derivative
ee= e;
u= Kp*e+Ki*z+Kd*ce; % PID control

du= MyTimeDelay(id,u); % Time delay


x= RK4(@plant, t, x, du, h); % Calls the plant
t= t+h;
end
end
7.2 Optimization of User-Defined Function
% Model of the plant
function xdot= plant(t,x,u)
K= 1; T= 10;
xdot= (-x+K*u)/T;
7.3 Optimization of Simulink Model
Procedure
Step 1 Create your simulink model.
- Define I/O variables and create them in model
workspace
- Set input signals, sampling time, and simulation time
Step 2 Code the program for simulating the model and
calculating the objective function.
- Define the objective function
Step 3 Close the simulink model and run the program
written in Step 2.
Step 4 Open the simulink model and run it.
7.3 Optimization of Simulink Model
Example 4. Tune the PID gains in terms of
minimizing the objective function:

r+ e 1 u e 3s y
Kp+Ki +Kds
- s 10 s  1

 
Minimize f  0
| r  y | dt  
0
| e | dt

s.t. 0  Kp,Ki,Kd  5
7.3 Optimization of Simulink Model
 If you enter variables, undeginated ones highlight
red color.
 You need to create them in model workspace.
7.3 Optimization of Simulink Model

 Double click the variable block and create it in


model workspace.
 If you are asked to enter a value, pass it.
7.3 Optimization of Simulink Model

 Open Modeling  Model explorer and select Model


Workspace.
 Check your variables or enter other parameters if
needed.
7.3 Optimization of Simulink Model
function Tune_PIDModel
clear all
options= optimoptions('ga','PlotFcn',@gaplotbestf);
options.PopulationSize= 30;
options.MaxGenerations= 20; % Increase value if needed
nvar= 3; % Number of parameters
LB= [0.0001 0.0001 0.0001]; % Lower bound
UB= [5 5 5]; % Upper bound of tuning parameters
[x,fval]= ga(@EvalObj,nvar,[],[],[],[],LB,UB,[],options)
7.3 Optimization of Simulink Model
% Updates Kp, Ki and Kd in simulink model workspace
simulink_model= 'PIDModel';
load_system(simulink_model);
gains= get_param(simulink_model,'modelworkspace');
gains.assignin('Kp', x(1));
gains.assignin('Ki', x(2));
gains.assignin('Kd', x(3));
7.3 Optimization of Simulink Model
function obj= EvalObj(x)
% Updates the values of Kp, Ki and Kd in model workspace
simulink_model= 'PIDModel';
load_system(simulink_model);
gains= get_param(simulink_model,'modelworkspace');
gains.assignin('Kp', x(1));
gains.assignin('Ki', x(2));
gains.assignin('Kd', x(3));

% Simulates the simulink model to get the outputs


simOut= sim(simulink_model,'SaveOutput','on');
7.3 Optimization of Simulink Model
% Retrieves time t and error e
t= simOut.find('t');
e= simOut.find('e');

% Calculate a performance index


n= length(e);
ee= abs(e);
obj= 0;
for i= 2:n
stepsize= t(i)-t(i-1);
obj= obj+0.5*(ee(i-1)+ee(i))*stepsize; % IAE
end
7.3 Optimization of Simulink Model
Q&A
Q&A

You might also like