ODE Simulink
ODE Simulink
HERMAN
S O LV I N G D I F F E R E N T I A L E Q U AT I O N S
USING SIMULINK
R . L . H E R M A N - V E R S I O N D AT E : J U LY 3 , 2 0 1 6
Copyright 2016 by R. Herman
published by r. l. herman
This text has been reformatted from the original using a modification of the Tufte-book documentclass in LATEX.
See tufte-latex.googlecode.com.
solving differential equations using simulink by Russell Herman is licensed under a Creative Com-
mons Attribution-Noncommercial-Share Alike 3.0 United States License. These notes have resided at
http://people.uncw.edu/hermanr/mat361/simulink since Summer 2015.
1 Introduction to Simulink 1
1 Solving an ODE . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
2 Handling Time in First Order Differential Equations . . . . . 7
3 Working with Simulink Output . . . . . . . . . . . . . . . . . . 11
4 Printing Simulink Scope Images . . . . . . . . . . . . . . . . . 13
5 Scilab and Xcos . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
6 First Order ODEs in MATLAB . . . . . . . . . . . . . . . . . . 19
Symbolic Solutions . . . . . . . . . . . . . . . . . . . . . . . . . 20
ODE45 and Other Solvers. . . . . . . . . . . . . . . . . . . . . . 20
Direction Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1 Linear Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
2 Nonlinear Models . . . . . . . . . . . . . . . . . . . . . . . . . . 63
7 Difference Equations 71
9 Index 75
1
Introduction to Simulink
We will view this as a system in which the input, x 0 = 2 sin 3t 4x, is fed
into an integrator and the output will be x (t). Generally, we have
Z
x (t) = x 0 (t) dt.
In order to carry this out, we separately insert the terms 2 sin 3t and
4x into the integration procedure. Since we do not know 4x, we take
the output from the integrator, multiply it by 4, and subtract that from
2 sin 3t. This combined set of terms is then feed back into the integrator.
This is shown schematically in Figure 1.3.
The simulation in Simulink carries out this procedure and takes the
form shown in Figure 1.4. In the background Simulink uses one of
MATLABs ODE solvers, numerical routines for solving first order dif-
ferential equations, such as ode45. This system uses the Integrator block
1 dx
s to integrate , producing x (t). The Scope is used to plot the out-
Integrator
dt
put of the Integrator block, x (t).
introduction to simulink 3
The input for the Integrator is the right side of the differential Equation
(1.1), 2 sin 3t 4x. The sine function can be provided by using the Sine
Wave block, whose parameters are set in the component. In order to get
4x, we grab the output of the Integrator (x) and boost it by changing the
Gain value to "4." Then, using the Sum component, these terms are added,
or subtracted, and fed into the integrator. That is the main idea behind
solving this system.
1
Gain
Connect the output of the Sum block to the input of the Integrator
block. [Figure 1.6.]
Right-click the Gain control and choose Flip Block under Rotate &
Flip. Double-click the Gain block and change the Gain block value
from 1 to 4. It should change on the control.
4 solving differential equations using simulink
Double-click the Sine Wave block and change the frequency to 3 rad/s
and the amplitude to 2. [See Figure 1.8] Set the time dropdown menu to
Use Simulation Time.
Connect the Gain output to the negative input of Sum and the Sine
Wave output to the positive input on the Sum control. [Note: The Gain
can be set to a negative value and connected to a + node in the Sum
block to obtain the same effect.]
To add a node to route an x value to the Gain, hold the CTRL key and
click on the Output line of the Integrator and drag towards the input
of the Gain. You can also Right-Click the line where you want the node
and drag from there to the Gain block. See Figure 1.9.
1
Gain
One can annotate the diagram by clicking near where labels are needed
and typing in the text box. This leads to the model in Figure 1.10.
Save the file under a useable file name. This file can be called in
MATLAB, or one can use the run button to run the simulation.
Double-click the Scope to see the solution. Figure 1.11 shows the Scope
plot after using the autoscale ( ) feature to rescale the scope view.
A little effort is needed to change the plot attributes and to import the
plots into working documents. This will be discussed in Section 1.4.
Also, one can make further changes to the system by checking the Con-
figuration Parameters under the Simulation menu item. See Figures
1.12-1.13. In particular, changing the Refine Factor can lead to smoother
solutions. The solution shown in Figure 1.11 had a setting of 1 and that
in Figure 1.14 is the result of setting the Refine Factor to 10.
externally feed the initial condition into the block. Double-click the Inte-
grator block and change the initial condition source from internal to exter-
nal. This adds another input to the block. Drag a Constant block from the
Sources group into the model, connect it to the new input, and change the
constant value to the desired initial value. This results in the simulation
shown in Figure 1.15.
dy 2
= y, where y(1) = 1. (1.2)
dt t
8 solving differential equations using simulink
ln |y| = 2 ln |t| + C = ln t2 + C.
y(t) = At2 ,
where A = eC .
Using the initial condition, we have the solution, y(t) = t2 .
We can set up the problem in Simulink as shown in Figure 1.16 for the
initial value problem
dy 2
= y,
dt t
where y(1) = 1. Running the simulation, we obtain the solution shown in
Figure 1.17.
The solution looks like y(t) = t2 . We can verify this by plotting t2 along
with the solution t see if they are the same. Another method would be to
introduction to simulink 9
compute the difference between the numerical and exact solution, y(t) t2 .
In order to do this, we add a Math Function block, selecting the square
function and connect it to the time route and a Sum Block. The solution is
also fed into the latter block and the difference is fed into a second Scope
Block. This is shown in Figure 1.18.
The result of the simulation is shown in Figure 1.19. We note that this is
the numerical error, though the solution is only off by 1.4 105 over the
given interval. Considering that the solution at t = 10 is Y (10) = 100, this
is a relative error of roughly 107 . That seems perfectly acceptable.
dy 2
= y + t2 .
dt t
10 solving differential equations using simulink
t2 y
Figure 1.20: Linear first order differen-
u2 dy/dt 1 tial equation model.
s
t Math Integrator1 Scope1
Function2
Clock 2/t y
1 1/t 2/t 2
2 y' = 2/t y+t , y(1)=1
u
Math Gain1
Product1
Exact solution: y(t) = t3
Function1
The model for this problem is shown in Figure 1.20. Running the sim-
ulation, we obtain the numerical solution, y(t) = t3 , as shown in Figure
1.21. Computing the difference between the numerical and exact solutions
in this case, we find the error is about 6 105 .
Example 1.3. Consider the initial value problem,
dx
= 2 sin 3t 4x, x (0) = 0. (1.6)
dt
This is the example that we first solved using Simulink. It is an-
other linear first order differential equation. The integrating factor is
found to be Z
(t) = exp 4 dt = e4t .
introduction to simulink 11
2/25
Sine Wave1 Scope
Gain
Sine Wave
100
80
60
y
40
20
0
1 2 3 4 5 6 7 8 9 10
t
Once you have exported your data to the MATLAB workspace and
created a plot, then you can use the menu items under Tools to annotate
the plot. Once you are satisfied with the Figure, go to the Edit menu and
select Copy Figure. Go to your report document and Paste (CTRL-V) the
figure into your document. You can then resize the figure, center it, and
add a numbered Figure caption describing the figure. Other methods for
recording Simulink Scope images and the Simulink model are described
next.
introduction to simulink 13
Method 1:
Select the Scope figure window in Figure 1.25, then hit ALT+PrintScrn
to copy the figure to a clipboard and paste the figure into your application.
You might want to change the colors before copying the scope image.
Click the Scope Parameters icon (2nd icon) and go to the Style tab as seen
in Figure 1.26. Change the Figure Color to black, Axes Colors to white
background and black writing, and Line Color to black. The selection of
these parameters is shown in Figure 1.26.
Now the Scope plot looks like Figure 1.27.
Method 2:
Go to Scope Parameters and select the History tab. Check the Save
data to workspace box. Note the variable name. Lets change the name to
MyScopeData for this example. Saving with Structure with time will save
the data as a structure. Run the simulation again.
Now, go into the MATLAB command window. You should see the
MyScopeData data in the variable list. Type
plot(MyScopeData.time, MyScopeData.signals.values)
This gives the MATLAB plot in Figure 1.29 which can be manipulated
14 solving differential equations using simulink
Method 3:
You can save the scope image as a jpg image. Create the MATLAB code
in Table 1.1. Save this code as an m-file with a name like prfig.m. In MAT-
introduction to simulink 15
0.8
0.6
0.4
0.2
-0.2
0 1 2 3 4 5 6 7 8 9 10
LAB run prfig (type prfig in the Command Window.) It should produce
the file mypic.jpg in your MATLAB folder. Of course, you can change the
name of the image before running prfig.m.
Now you can Insert the figure into your MS Word document as a Pic-
ture file.
Method 4:
You can add a To Workspace block to your simulation. This will auto-
matically place the data in the MATLAB space. Go to the Simulink library
16 solving differential equations using simulink
and add a To Workspace block to your model. Connect this block to the
input to the Scope (right click the input line and drag to connect to the To
Workspace block.) This will give the connection as shown in Figure 1.31.
You can double-click this block and change the variable name that will
be saved. Lets assume it is simout. Then, run the simulation. Go into
MATLAB and type
plot(simout.time,simout.data)
This will give you a plot of the Scope data. Now you can print, save
as an image, or copy (under Edit) to an MS Word document. Below is
what you get using Copy Figure under the Edit menu item in the Figure
window.
Printing Models
Once you have made a model, you might want to include it in a report.
It is easy to capture a model, but a complicated model might not print
large enough to see the component annotations.
First open the desired model. Then, in MATLAB you can use the print
command to print the model. For example, typing the following in the
MATLAB command window prints the open model to an encapsulated
postscript file:
In order to run the simulation, one can click the play icon or select
introduction to simulink 19
Start under the Simulation menu item. The ODE solver can be changed
through Setup under the Simulation menu. The solution is shown in
Figure 1.37.
The blocks are not labeled like Simulink. One can label the blocks by
right-clicking and selecting Edit under the Format item. There one can
enter text to appear with the block. Annotation of the workspace is done
by selecting a Text_f block and adding text to it and changing the fontsize.
Sample annotations are shown in Figure 1.38.
Symbolic Solutions
sol = dsolve(Dx=2*sin(t)-4*x,x(0)=0,t);
ezplot(sol,[0 10])
xlabel(t),ylabel(x), grid
sol =
(2 exp(-4 t))/17 - (2 171/2 cos(t + atan(4)))/17 Figure 1.39: The solution of Equation
(1.1) with x (0) = 0 found using
0.5
MATLABs dsolve command.
0.4
0.3
0.2
0.1
0
x
-0.1
-0.2
-0.3
-0.4
-0.5
0 1 2 3 4 5 6 7 8 9 10
t
[t y]=ode45(func,[0 5],1);
plot(t,y)
xlabel(t),ylabel(y)
title(y(t) vs t)
introduction to simulink 21
function f=func(t,y)
f=-t*y/sqrt(2-y.^2);
0.7
0.6
0.5
y
0.4
0.3
0.2
0.1
0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
t
One can also use ode45 to solve higher order differential equations. Sec-
ond order differential equations are discussed in Section 4. See MATLAB
help for other examples and other ODE solvers.
Direction Fields
The mesh command sets up the xy-grid. In this case x is in [0, 2] and y
is in [0, 1.5]. In each case the grid spacing is 0.1.
We let dy = 1-y and dx =1. Thus,
dy 1y
= = 1 y.
dx 1
22 solving differential equations using simulink
1
y
0.5
0
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
x
One can add solution, or integral, curves to the direction field for dif-
ferent initial conditions to further aid in seeing the connection between
direction fields and integral curves. One needs to add to the direction field
code the following lines:
hold on
[t,y] = ode45(@(t,y) 1-y, [0 2], .5);
plot(t,y,k,LineWidth,2)
[t,y] = ode45(@(t,y) 1-y, [0 2], 1.5);
plot(t,y,k,LineWidth,2)
hold off
1
y
0.5
0
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
x
introduction to simulink 23
1.7 Exercises
1. Construct the model in Figure 1.4 for solving the initial value problem
dx
dt = 2 sin 3t 4x, x (0) = 0, and produce a plot of the solution.
dx
2. Modify the model in the Problem 1. to solve = f (t) 2x for a
dt
different function, f (t) and initial condition.
3. Solve the following initial value problems using MATLAB (See Section
1.6) and Simulink. Are the solutions the same? Provide plots of the
solutions.
a. y0 = xy, y(0) = 1.
b. y0 = 2y(3 y), for different initial conditions, y(0) = 4,
y(0) = 2, and y(0) = 1.
c. y0 = 1 + x + y, y(0) = 1.
d. y0 = (y2 4)(y 4) for different initial conditions, y(0) = 5,
y(0) = 3, y(0) = 1, y(0) = 1, and y(0) = 3.
a. y0 = xy.
b. y0 = 2y(3 y).
c. y0 = 1 + x + y.
d. y0 = (y2 4)(y 4).
2
First Order Differential Equations
dy 2
= y, y(1) = 1, (2.1)
dt t
dy 2
= y + t2 , y(1) = 1, (2.2)
dt t
dx
= 2 sin 3t 4x, x (0) = 0. (2.3)
dt
The Simulink models were provided in Figures 1.16, 1.20, and 1.4, respec-
tively.
In this chapter we solve a few more first order equations in the form of
applications. These will include growth and decay, Newtons Law of Cool-
ing, pursuit curves, free fall and terminal velocity, the logistic equation,
and the logistic equation with delay.
Here we have denoted the birth rate as b and the mortality rate as m. This
gives the total rate of change of population as
dP
= bP mP kP, (2.4)
dt
26 solving differential equations using simulink
where k = b m.
Equation (2.4) is easily modeled in Simulink. All of the needed blocks
are under the Commonly Used Blocks group. We need an Integrator, Con-
stant, Gain, and a Scope block. The output from the Integrator can be
feed into a Gain control, which represents k, and the output from the
Gain, kP, can then be used as an input to the Integrator. We add the
Scope in order to plot the solution. The model is shown in Figure 2.1.
Note that a Constant block was added to provide an external input of the
initial condition.
The exact solution is easily found noting that Equation (2.4) is a separa-
ble equation. Rearranging the equation, its differential form is
dP
= k dt.
P
Integrating, we have
dP
Z Z
= k dt
P
first order differential equations 27
ln | P| = kt + C. (2.5)
| P(t)| = ekt+C
P(t) = ekt+C
= Aekt . (2.6)
P(t) = P0 ekt .
In the Simulink model, the initial value was given as P(0) = 10 and k =
0.5. Therefore, the solution in Figure 2.2 is of the function P(t) = 10e0.5t .
Equation (2.4) is the familiar exponential model of population growth: Malthusian population growth.
dP
= kP.
dt
We obtained solutions exhibiting exponential growth (k > 0) or decay
(k < 0). This Malthusian growth model has been named after Thomas
Robert Malthus (1766-1834), a clergyman who used this model to warn
of the impending doom of the human race if its reproductive practices
continued. Later we modify this model to account for competition for
resources, leading to the logistic differential equation.
If you take your hot cup of tea, and let it sit in a cold room, the tea
will cool off and reach room temperature after a period of time. The law
of cooling is attributed to Isaac Newton (1642-1727) who was probably
the first to state results on how bodies cool.1 The main idea is that a body 1
Newtons 1701 Law of Cooling is
at temperature T (t) is initially at temperature T (0) = T0 . It is placed in an approximation to how bodies cool
for small temperature differences
an environment at an ambient temperature of Ta . The goal is to find the (T Ta T) and does not take into ac-
temperature at a later time, T (t). count all of the cooling processes. One
account is given by C. T. OSullivan,
We will assume that the rate of change of the temperature of the body Am. J. Phys (1990) p 956-960.
is proportional to the temperature difference between the body and its
surroundings. Thus, we have
dT
T Ta .
dt
The proportionality is removed by introducing a cooling constant,
dT
= k( T Ta ), (2.7)
dt
where k > 0.
28 solving differential equations using simulink
T (t) Ta = ( T0 Ta )ekt ,
or
T (t) = Ta + ( T0 Ta )ekt .
Example 2.1. A cup of tea at 90o C cools to 85o C in ten minutes. If the
room temperature is 22o C, what is its temperature after 30 minutes?
Using the general solution with T0 = 90o C,
85 = T (10)
= 22 + 68e10k
63= 68e10k
63
e10k = 0.926
68
10k = ln 0.926
ln 0.926
k =
10
0.00764min1 .
T (t) = 22 + 68e0.00764t .
T0
Integrator
20
Newton's Law of Cooling
Ta T' = - k (T-T0)
Next we model Equation (2.7) in Simulink. The input for the integrator
is simply k( T Ta ). We need to define the constants k and Ta . We will
first order differential equations 29
How good is the solution? We can solve the problem by hand for this
set of parameters. However, we will take this opportunity to introduce
the idea of a subsystem and set up a model in which we can interactively
modify the constants and get Simulink to automatically provide the exact
solution for comparison.
3
Newton's Law of Cooling
T ambient
T' = - k (T-T0)
We begin by replacing the scope with an output block. The Out1 block
can be found in the Sink group. The input to the subsystem will be the Creating a subsystem.
three parameters, k, T0 , and Ta . Each of these constant blocks in Figure 2.3
will be replaced by an In1 block, found in the Sources group. In Figure 2.5
the three inputs and one output are now oval blocks.
Double-click each of the three input blocks, one at a time, and set the
Port Number of k, T0 , and Ta , to 1, 2, and 3, respectively. Finally, rename
each of these controls using the labels that make sense, such as k for k. In
Figure 2.5 we show the subsystem that we have created.
Now highlight the entire subsystem using CTRL-A. In the menu sys-
30 solving differential equations using simulink
tem, look for Create Subsystem from Selection. In the 2015 version, this
is under the menu item Diagram and subitem Subsystem & Model Ref-
erence. Rearranging the resulting subsystem, one has something like the
subsystem block in Figure 2.6. This is the equivalent of a black box with
three inputs and one output.
Next, we can make use of the subsystem just created. Replace the three
input ports with constant blocks. Rename the Constant blocks with the
parameter name and fill each block with a value. The output port can be
replaced with a Scope block, or any other form of output desired. This can
be seen in Figure 2.7.
Before finishing with this model, we will build in the exact solution.
Recall that the general solution can be written in terms of the parameters
as
T (t) = Ta + ( T0 Ta )ekt .
So, we can feed the values of the parameters in the model into a Fcn block
and output the exact solution for comparison. We will also need a time
value. So, we will need the Clock block as well.
60 T(0) T(t)
IC Scope
20 T ambient
Ta
Cooling System
The entire model is shown in Figure 2.8. The subsystem is labeled Cool-
ing System The top portion is a repetition of the Newtons Law of Cooling
model implemented previously.
We have added a Fcn block from the User-Defined Functions group.
The input will be a vector containing all of the variables in the exact solu-
tion. This is accomplished by adding a Mux (or Multiplex) block. Double-
click the Mux block and set the number of inputs to 4.
Now, double-click the Fcn block and enter the exact solution in the form
u(1)+u(2)*exp(-u(3)*u(4))
Here we have assumed that the variables are fed into the Mux block in the
order Ta , T0 Ta , k, and t. In Figure 2.8 one can see how the values are
first order differential equations 31
60 T(0) T(t)
IC Scope
20 T ambient
Ta
Cooling system
Exact Solution
f(u)
Fcn Scope1
Clock
y (t) = g. (2.8)
where f (v) gives the resistive force and mg is the weight. Note that this
applies to free fall near the Earths surface. Also, for f (v) to be a resis-
tive force, f (v) should oppose the motion. If the body is falling, then f (v)
32 solving differential equations using simulink
should be positive. If the body is rising, then f (v) would have to be nega-
tive to indicate the opposition to the motion.
We will model the drag as quadratic in the velocity, f (v) = bv2 .
Example 2.2. Solve the free fall problem with f (v) = bv2 .
The differential equation that we need to solve is
v = kv2 g, (2.10)
where k = b/m. Note that this is a first order equation for v(t).
Formally, we can separate the variables and integrate over time to
obtain Z v
dz
t+C = . (2.11)
kz2 g
If we can do the integral, then we have a solution for v. One way to
evaluate this integral is to use Partial Fraction Decomposition.
When there are two linear factors in the denominator, the integral
can be rewritten as
Z
dx 1 1 1
Z
= dx (2.12)
( x a)( x b) ba xa xb
The new integral has two terms which can be readily integrated.
In order to factor the denominator in the current problem, we
first have to rewrite the constants. We let 2 = g/k and write the
integrand as
1 1 1
= . (2.13)
kz2 g k z2 2
Now we use a partial fraction decomposition to obtain
1 1 1 1
= . (2.14)
kz2 g 2k z z +
The integrand can be easily integrated giving
1 v
t+C = ln . (2.15)
2k v +
Solving for v, we have
1 Ae2kt
v(t) = , (2.16)
1 + Ae2kt
where A eC . A can be determined using the initial velocity.
There are other forms for the solution in terms of a tanh function, which
the reader can determine as an exercise. One important conclusion is that
forqlarge times, the ratio in the solution approaches 1. Thus, v =
gk as t . This means that the falling object will reach a constant
terminal velocity.
Equation (2.10) can be modeled in Simulink. The model is shown in
Figure 2.9. The solution for k = 0.00159m1 , which is found for the above
sample computation, is shown in Figure 2.10. Weq see that terminal velocity
g
is obtained and matches the predicted value, k = 78 m/s.
first order differential equations 33
Constant1
Scope
0.00159 u2
( a, vt)
( x, y)
x
( a, 0)
2 1 y'
xos 1
w xos
Integrator
Integrator1 Scope
0 0
Clock
Product y'(0) y(0)
9.000001
Constant
5.997
u(3)*u(2)*u(1)/(u(1)^2-u(2)^2) 6
Display
Fcn1
dx
Z
= ln | a x | + c1 .
ax
The left hand side takes a little extra work, or looking the value up
in Tables or using a CAS package. Recall a trigonometric substitution
is in order. We let z = tan . Then dz = sec2 d. The methods
proceeds as follows:
dz sec2
Z Z
= d
1 + z2
Z
1 + tan2
= sec d
= ln(tan + sec ) + c2
p
= ln(z + 1 + z2 ) + c2 . (2.18)
p x v
w
ln(z + 1 + z2 ) = ln
a
p x v
w
z+ 1 + z2 = . (2.19)
a
We can solve for z = y0 , to find
1 x wv x wv
0
y =
2 a a
Integrating,
" v
x 1+ w
v
x 1 w
#
a a a
y( x ) = + k.
2 1 + wv 1 wv
Can the dog catch the cat? This would happen if there is a time
when y(0) = vt. Inserting x = 0 into the solution, we have y(0) =
avw
w2 v2
= vt. This is possible if w > v.
dy
= by my, (2.21)
dt
where we had defined the birth rate as b and the mortality rate as m.
Generally, these rates could depend on the time. In the case that they
are both constant rates, we can define k = b m and obtain the famil-
iar exponential model of population growth. When populations get large
enough, there is competition for resources, such as space and food, which
can lead to a higher mortality rate. Thus, the mortality rate may be a func-
tion of the population size, m = m(y). The simplest model would be a
+ cy. Then, the previous exponential model The logistic model was first published
linear dependence, m = m
in 1838 by Pierre Franois Verhulst
takes the form (1804-1849) in the form
dy
= ky cy2 , (2.22)
dN N
dt = rN 1 ,
dt K
where k = b m. This is known as the logistic model of population growth. where N is the population at time t, r is
Typically, c is small and the added nonlinear term does not really kick in the growth rate, and K is what is called
the carrying capacity. Note that in this
until the population gets large enough.
model r = k = Kc.
Example 2.4. Show that Equation (2.22) can be written in the form
z0 = kz(1 z)
y0 = ky cy2
z0 = kz c2 z2 ,
or c
z0 = kz 1 z .
k
Thus, we obtain the result, z0 = kz(1 z), if we pick = kc .
The point of this derivation is to show that there is only one free param-
eter, k, and that many combinations of c and k in the original problem lead
to essentially the same solution shape.
We can model the logistic equation, y0 = ry(1 y), with r = 1 and
y(0) = 0.1 in Simulink. The model is shown in Figure 2.14. Running te
model gives the solution in Figure 2.15. It shows the typical sigmoidal
curve bounded by the solutions y = 0 and y = 1.
38 solving differential equations using simulink
Product 1-y
y' = r y (1-y)
1
Constant
Sometimes the rate of change does not immediately take place when
the system changes. This can be modeled using differential-delay equa-
tions. For example, when the resources are being depleted, the effects
might be delayed. So, a possible model would be the logistic equation with
delay,
y0 = ry(t)(1 y(t )),
where is a fixed delay time.
The problem with trying to solve this model at time t is that we need
to know something about the solution for earlier times, y(t ). One way
to tackle the problem is to specify the solution for times [0, ] and then
to solve the equation with delay using this starting value. So, if y = 2
first order differential equations 39
2
y' 1 y
Alpha >= 1
s
Integrator Scope
Clock
Switch to enter y=2
for t<=1
0
Solve y'=0
y
2.7 Exercises
and the body temperature of the person was 98.6o F at the time of death,
determine when the murder occurred.
3
Second Order Differential Equations
y00 ( x ) = F ( x, y( x ), y0 ( x )).
y00 R y0 R y
(c) input output
F(x, y, y0 )
ay00 + by0 + cy = 0
in Simulink.
The simulation in Figure 3.3 solves the equation
y00 + 5y0 + 6y = 0
Second Order Constant Coefficient ODE Figure 3.3: Second Order Constant
Coefficient ODE.
y'' 1 y' 1 y
s s
Integrator Integrator1 Scope
b/a y'
5
b/a
c/a y
6
c/a
0.1
y
0.05
0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
x
1 c k
x 00 = F (t) x 0 x.
m m m
Scope
1
Step 1/m
x'' 1 x' 1 x
s s
Integrator Integrator1 Scope1
0.5
c/m
XY Graph
2
k/m
This suggests a model like that shown in Figure 3.5. In this exam-
ple the forcing term was taken as a step function.
(
0, t < 1,
F (t) =
1, t 1.
directly upward, the drag is negative, opposing the motion. The model
will need functions to compute the speed, v, and will need two integrators
with appropriate initial position and velocity. The gravitational force will
also be provided with a constant block. This model is shown in Figure 3.8
The model is done in British units (foot-pound-second). The initial
position is [0, 4] ft and the initial velocity is [80, 80] ft/s. The gravitational
constant is g = [0, 32] ft/s2 . The value of the drag coefficient does not
show in the figure. It can be made to show if the Gain block is resized.
The position and speed vs time plots are shown in Figure 3.9. Note that
changing the simulation time is one way to only display the time that the
mass is above y = 0. Also, the plot of speed shows that the speed is always
positive.
Also shown in this model is the use of the XY Graph block. This takes
two inputs in order to plot the path y vs x. XY Graphs automatically plot
when the simulation is run, as opposed to the Scope plots, which need to
be double-clicked to show the plots. One needs to double-click the block to
change the scale shown. For this model the output is shown in Figure 3.10.
This plot is useful for determining the maximum height and range of the
projectile.
[x'',y'']
1 [x',y']
xos 1 [x,y]
xos
Integrate x''
Integrate x'
XY Graph
[80,80] [0,4]
Initial Velocity Initial Position
y vs t
u
Product Dot Product Sqrt v vs t
gravitational
[0,-32] acceleration -K-
Drag Coefficient
The ball satisfies the second order equation x 00 = g. Noting that the
velocity is v = x 0 , this can be written as two first order equations,
x 0 = v,
v0 = g. (3.1)
This system can be used to produce the Simulink model in Figure 3.11,
where we have introduced initial conditions x (0) = 3 and v(0) = 0. Here
the 2 2 matrix is entered in the gain and the acceleration term is added
separately. In order to plot the position vs time, we put a Demux block to
separate out the components of the state vector and added a Terminator
block to terminate one of the branches.
The output of the simulation, which was run for a time of 1 second is
shown in Figure 3.12. Note that the ball has fallen below ground level.
We wish to allow for the ball to bounce from the ground. We will need to
test to see when x 0 and v 0. This is accomplished by adding some
conditions to the Integrator block.
Double-click the Integrator block and set the External reset to rising.
This will add a third input as shown in Figure 3.13. Then, replace the
initial condition Constant block with an IC block. This is found in the
Signal Attributes group. It looks like the IC block in Figure 3.13.
Next, we need to enter the conditions determining when the block hits
the ground and change the block velocity. The input to the condition con-
sist of the Boolean condition, (u[1]<=0)&&(u[2]<0), and the new position
and velocity. Here u[1] and u[2] are the position and velocity components.
We set the position as u[1] and the velocity as -0.8*u[2]. These expressions
are entered using Fcn blocks from the User-Defined Function group. This
50 solving differential equations using simulink
model is shown in Figure 3.14 with the needed connections to the Fcn
blocks and the Integrator block. This output is shown in Figure 3.15.
Bouncing Ball
x'=v
v'=-g [0;-9.8]
Integrator
Acceleration
[x,v]'
[0 1;0 0]* u
x
1 [x,v] Scope
(u[1]<=0)&&(u[2]<0) v
Gain s
Fcn
[3;0] Terminator
xo
u[1]
Fcn1
IC
-0.8*u[2]
Fcn2
We can also use ode45 to solve second and higher order differential
equations. The key is to rewrite the single differential equation as a system
of first order equations. Consider the simple harmonic oscillator equation,
x + 2 x = 0. Defining y1 = x and y2 = x,
and noting that
x + 2 x = y 2 + 2 y1 ,
second order differential equations 51
we have
y 1 = y2 ,
y 2 = 2 y1 .
Here [0 5] gives the time interval and [1 0] gives the initial conditions
The function func is a set of commands saved to the file func.m for
computing the righthand side of the system of differential equations. For
the simple harmonic oscillator, we enter the function as
function dy=func(t,y)
omega=1.0;
dy(1,1) = y(2);
dy(2,1) = -omega^2*y(1);
plot(t,y(:,1))
xlabel(t),ylabel(y)
title(y(t) vs t)
plot(y(:,1),y(:,2))
xlabel(y),ylabel(v)
title(v(t) vs y(t))
0.6
0.4
0.2
0
y
-0.2
-0.4
-0.6
-0.8
-1
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
t
0.6
0.4
0.2
0
v
-0.2
-0.4
-0.6
-0.8
-1
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1
x
clear
[x,y]=meshgrid(-2:.2:2,-2:.2:2);
dx=y;
dy=-x;
quiver(x,y,dx,dy)
axis([-2,2,-2,2])
xlabel(x)
ylabel(y)
hold on
[t y]=ode45(func,[0 6.28],[1 0]);
plot(y(:,1),y(:,2))
hold off
0.5
0
y
-0.5
-1
-1.5
-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
x
3.5 Exercises
3. Consider the model in Figure 3.19. Fill in the question marks with the
correct expression at that point in the computation. What differential
equation is solved by this simulation?
a. x2 y00 + 3xy0 + 2y = 0.
b. x2 y00 3xy0 + 3y = 0, y(1) = 1, y0 (1) = 0.
c. x2 y00 + 5xy0 + 4y = 0.
54 solving differential equations using simulink
What does this model solve? Figure 3.19: Mystery model for Problem
4.
?
1 ?
0 xos 1 ?
1 xos
y'(0) Integrator
y(0) Integrator1 Scope
3 ?
b Divide Clock
?
u2
10
Math
c Divide1 Function
6. A certain model of the motion light plastic ball tossed into the air is
given by
mx 00 + cx 0 + mg = 0, x (0) = 0, x 0 (0) = v0 .
Here m is the mass of the ball, g=9.8 m/s2 is the acceleration due to
gravity and c is a measure of the damping. Since there is no x term, we
can write this as a first order equation for the velocity v(t) = x 0 (t) :
mv0 + cv + mg = 0.
mx 00 + bx 0 + kx = u(t). (4.1)
b k 1
x10 = x x2 + u ( t )
m 1 m m
x20 = x1 (4.2)
Note that x200 = x10 gives the second order equation with x = x2 . Also, this
is not the typical order of equations usually encountered when studying
systems of differential equations. This order is chosen to be consistent with
the State Space Block which we will use later.
This system can be written in matrix form: x0 = Ax + Bu, where
" #
x1
x= ,
x2
b k
A= m m ,
1 0
1
B = m .
0
y = Cx + Du,
56 solving differential equations using simulink
The whole process is captured in the State Space Block. This block is
found in the Continuous group. The implementation of this system with
a sinusoidal forcing term is depicted in Figure 4.2. This shows the pair of
equations
x0 = Ax + Bu,
y = Cx + Du. (4.3)
C = [0, 1], and D = 0. These values are put into the block by going into the
Function Block Parameters dialog box for the State Space block as shown
in Figure 4.3. Note that there is a place to enter the initial condition, such
as [ x1 (0), x2 (0)] T = [0, 1] T . In this case one would type [0; 1]. A compari-
son of outputs from using this initial condition to zero initial conditions is
shown in Figure 4.4. Figure 4.5 shows the system needed to produce this
plot.
State-Space1
58 solving differential equations using simulink
and C = [0, 0.5], This differs from what we derived above. The difference
lies in the fact that we can multiply B by any constant and divide C by
that constant and not affect the solution of the problem. In this case, the
constant in question is the mass, m = 2.0.
x0 = ax + by
0
y = cx + dy. (5.1)
This can be modeled using two integrators, one for each equation. Due to
the coupling, we have to connect the outputs from the integrators to the
inputs.
As an example, we show in Figure 5.1 the case a = 0, b = 1, c = 1,
d = 0. This is the linear system of first order equations for x 00 + x = 0, and
y = x 0 . We also insert the initial conditions x (0) = 1, y(0) = 2. Running the
model, results in the plots in Figures 5.2 and 5.3.
b
x
0
a
1 x
1 xo s
Integrator
x(0)
Scope XY Graph
1 y
2 xo s
Integrator1
y(0) Linear System of Differential Equations
y x'=ax+by
0 y'=cx+dy
d
x
-1
c
60 solving differential equations using simulink
y
Scope XY Graph
0 1
-1 0 * u
Linear System of Differential Equations
Gain
the initial conditions to [1; 2]. The solution plots are the same as shown in
Figures 5.2 and 5.3.
Here are simulations of some nonlinear systems. The jerk model and Chua
circuit are typical models displaying complex behavior.
62 solving differential equations using simulink
sin(u)
-1 1
Fcn xos 1
Product Gain xos
Integrator
Integrator1
4
Constant
0 1
Constant1 Constant2
Linear Pendulum
x''+k x=0
Sine Wave Scope
-1 1
xos 1
4 Product1 Gain1 xos
Integrator2
Constant3 Integrator3
0 1
Constant4 Constant5
Van der Pol Equation Figure 5.7: van der Pol equation.
x''=mu (1-x^2)x'-x
x'' x' x
1-u^2 1 1
1 s s
Fcn Integrator Integrator1
Product Gain
Scope
xy y
Product Scope
0.01 1
xos
y' y
b Foxes
XY Graph
10
IC1
1
.33 s
Product1 Integrator2 R
gamma
systems of differential equations 65
1
a
1.1
b
0.42
c
1 |u| 5/7 x
9 x' 1 x
Constant Abs Product s
b
alpha Integrator
8/7 .5 XY Graph
1 |u| a Gain
y
y' 1
Constant1 Abs1 s
Integrator1 y
Chua's Circuit
Product1
x' = alpha [y - x + bx + 0.5(a-b)(|x+1|-|x-1|)]
z' 1 z
y' = x - y + z -100/7
s
z' = - beta y Integrator2 z
- beta
Gain y''
1 y' 1 y
yp xos s
Scope
Integrator Integrator1
Constant
y
y'' = 4(y-x), y(0) = 0, y(1) = 2.
To Workspace
2 4 2x -2x
y(x) = e (e - 1) (e - e ) + x
clear all;
N=20; % Number of iterations
beta=2; % Target value
yp=1; % y(0) guess
alpha=.1; % Fraction of difference
sim(BVPmodel)
for i=1:N
yp=yp-alpha*(y.signals.values(end,1)-beta);
sim(BVPmodel)
plot(tout,y.signals.values,b)
hold on
end
hold off
axis square
xlabel(x)
ylabel(y)
title(y vs x)
68 solving differential equations using simulink
1.5
1
y
0.5
0
0 0.2 0.4 0.6 0.8 1
x
7
Difference Equations
Scope
XY Graph
70 solving differential equations using simulink
y(n+1)
0.3
Z-1 y(n)
1.4
b
a Delay1
Math
u2 Function
1 0.5
Constant
y(0)
x(n+1)
XY Graph
Z-1 x(n)
Delay Scope
Henon Map
0.5 x(n+1) = 1-a x(n)^2 + y(n)
y(n+1) = b x(n)
x(0)
n-1 xn-1
.125 x_n
Clock1 Gain1
xn-1+ yn-1
simout
To Workspace
0.125
h(xn-1+ yn-1)
Gain
8
Partial Differential Equations
Product
1
-C- xos K*u 1
Integrator Gain k
ICs
-C-
BCs
Scope
9
Index