Вы находитесь на странице: 1из 18

ODE Solvers 1

ChE 441 Washington State University


Process Control Voiland School of Chemical Engineering and Bioengineering
Fall, 2011 Richard L. Zollars

Solving Differential Equations

Many problems in chemical engineering are naturally expressed as differential
equations. For example, in any rate driven process (heat transfer rate, mass transfer rate,
reaction rate) the rate may be expressed as a change per unit time, i.e., as a time
derivative. Similarly properties may not change in time but in space. As a fluid flows
down a pipe through a furnace its temperature increases. Thus the temperature of the
fluid changes with axial position in the pipe. A proper mathematical description would
thus involve a differential of the temperature with axial position, i.e. a dT/dz term.
Whenever one (or more terms) in an equation is described by a differential the resulting
equation will be a differential equation.

While it would be nice if we could solve every differential equation we encounter
(as you did in Math 315) more often than not analytic solutions to many of the
differential equations we face in chemical engineering either do not exist or are too
complex to derive. Thus we rely heavily on numerical techniques to solve the differential
equations we face. At present there are a wide variety of computer packages that include
differential equation solvers. In general these packages contain all of the input/output
and integration algorithms. All that you have to do, as a user, is to specify the equations
you want solved. In what follows two different packages will be examined for use as
differential equation solvers.

The Problem To Be Solved

For the software packages to be demonstrated we will solve the same problem,
which is given below. Consider a chemical reactor initially full of the compound A. A
undergoes a series reaction first to compound B then to compound C as shown below

C B A
k k
2 1


The following two differential equations can be written describing the change in the
concentration of A and B with time

B A
B
A
A
C k C k
dt
C d
C k
dt
C d
2 1
1
=
=


subject to the initial conditions
0 0
0 2
= = =
= = =
t at C C
t at C C
Bo B
Ao A


ODE Solvers 2

The values of the two rate constants are k
1
= 0.5 min
-1
and k
2
= 1.5 min
-1
. We wish to
obtain the values of the concentrations of A, B and C as a function of time for times up to
10 min. To obtain the concentration of C we could write a third differential equation

0 0
2
= = = = t at C C with C k
dt
C d
Co C B
C


or use a material balance to get

B A B A Co Bo Ao C
C C C C C C C C = + + = 2

We now will solve this problem using each of the packages starting with MathCAD.

MathCAD

The following is copied directly from a MathCAD program for the solution of the
problem stated above.


This is the solution to the example problem in MathCAD. We will solve the problem using the two
differential equations given and the material balance for compound C. The first step is to define a
vector that contains the initial values of the variables (CA and CB). Thus
y
2
0
|

\
|
|
.
:=
We now need to define a vector that tells the integrator how to compute the derivatives for CA and
CB. This is given by
D t y , ( )
0.5 y
0

0.5 y
0
1.5 y
1

|

\
|
|
.
:=


ODE Solvers 3
In the definition of D the first argument is the independent variable (in our case t since both
differential equations are time derivatives), while the second argument is a vector containing all
dependent variables (C
A
and C
B
in our problem).
Note that in this expression the variable y is itself a vector (a two component vector where the first
component is the value of C
A
and the second is C
B
). Remember that in MathCAD the subscripts in
vectors start with 0 not 1. Thus y
0
refers to C
A
and y
1
refers to C
B
.
We are now ready to integrate as we have both defined the initial values and the manner in which
the derivatives are to be computed. MathCAD offers us a number of different integrators; odesolve,
rkfixed. Bulstoer, and Rkadapt plus some other more specialized options. odesolv solves only a
single differential equation and will not be presented in this description. rkfixed used a fourth-order
Runge-Kutta integration algorithm with a fixed integration step size to solve sets of ODE's.
Bulstoer uses the Bulirsch-Stoer integration method that is slightly more accurate than the
Runge-Kutta technique. Rkadapt uses a variable step size integration algorithm that adjusts
according to how fast the solution is changing. The argument used to invoke any of these three is
the same - only the name of the algorithm changes. You may take a look at the Help feature in
MathCAD (under differential equations) for MathCAD's on-line help.
We'll use the Rkadapt algorithm for this example. The statement needed to start the integration
algorithm looks like
Rkadapt(y,x1,x2,npoints,D)
where y is the vector of initial values, x1and x2 are the endpoints of the integration interval, npoints
is the number of points (in addition to the initial value) we want calculated, and D is the vector that
defines how the first derivatives are to be evaluated. The initial values of y must be defined at the x1
value.
Let's now integrate this problem and store the results in an array called Z. The following command
completes the integration
Z Rkadapt y 0 , 10 , 100 , D , ( ) :=
where I have asked that the integration be reported at 100 points in addition to the initial value, thus
a total of 101 values for t, C
A
and C
B
. The array Z is thus a (101 x 3) array where the three rows
correspond to t, C
A
and C
B
. We now need to compute C
C
. This can be done as shown below.

i 0 100 .. :=
Z
i 3 , ( )
2 Z
i 1 , ( )
Z
i 2 , ( )
:=
We could have the array printed out but this would consume a lot of paper and large sets of
tabular data are not that understandable. Instead, let's plot the results.

0 5 10
0
1
2
2
0
Z
i 1 , ( )
Z
i 2 , ( )
Z
i 3 , ( )
10 0 Z
i 0 , ( )


ODE Solvers 4

This plot would work so long as you remember that Z(i,0) is t, Z(i,1) is C
A
, Z(i,2) is C
B
and Z(i,3) is C
C
. You can get the plot to look like the one below by doing the following.
Generate the plot as above. Now double click on the plot itself to get the chart formatting
menu. Select Traces from the menu. You'll see a table with various options. At the
bottom are the current selections. In the box that says trace 1 type in CA. Then select
trace 2 from the table and type in CB in the box at the bottom. Similarly for trace 3 as
CC. In the boxes below the table click off the Hide Legend selection and click on the
Hide Arguments selection. Now go to the Labels menu and type in the labels you want to
appear on the plot (t for the x axis and CA, CB, CC for the y axis. You may (and should)
also add a title. You now may exit the formatting menu by placing the cursor at some
other point on the MathCAD sheet and clicking. You will notice that whenever you have
selected a plot, i.e., it is surrounded by the blue border, both your labels and the actual
arguments (the Z's) will be displayed. When the plot is not highlighted only the labels
will be displayed if you've set the options as stated above.
0 5 10
0
1
2
CA
CB
CC
Example Problem
t
C
A
,

C
B
,

C
C
Finally, suppose you do want to see printed values but not all of them that are needed to produce a
smooth plot. Let's say you only want to see the values at every minute, including the original
values - a total of 11 values. You could do this by doing the following

ii 0 10 .. :=
j 0 3 .. :=
ZZ
ii j , ( )
Z
10 ii j , ( )
:=


ODE Solvers 5
ZZ
0 1 2 3
0
1
2
3
4
5
6
7
8
9
10
0 2 0 0
1 1.213 0.383 0.404
2 0.736 0.318 0.946
3 0.446 0.212 1.342
4 0.271 0.133 1.596
5 0.164 0.082 1.754
6 0.1 0.05 1.851
7 0.06 0.03 1.909
8 0.037 0.018 1.945
9 0.022 0.011 1.967
10 0.013 6.73810
-3
1.98
=


Matlab

There are a couple of things to remember about Matlab that will make its use
easier. It was developed to work with vectors and matrices. Thus many of its operations
(subroutines, etc.) are more easily used if your problem is expressed in a vector/matrix
format. When you open Matlab there will be heading then a >> symbol. This indicates
that Matlab is waiting for you to tell it to do something. If you want to assign a value to a
variable (say let x = 3) type this in and hit the return key. The result you will get is
shown below.


This is a Classroom License for instructional use only.
Research and commercial use is prohibited.
>> x=3

x =

3

>>

Note that below the line containing x = 3 Matlab has returned x = then on the next line 3.
This is just Matlab echoing back what you just commanded it to do. This can get tedious.
To avoid getting the echos simply end each line with a semicolon (;) as shown below

>> x = 3;
>>

Since the variable used above (x) has only a single value it can be entered in the usual
fashion. Suppose you wished to define a row vector (1 column, n rows). This is the
same as a 1xn matrix. To enter values into a matrix in Matlab enter the name of the
matrix (lets use y) and equal sign then a square bracket ([). The square bracket lets
Matlab know that what will follow is a matrix (array). Separate entries in a row by

ODE Solvers 6
spaces; separate rows by using a semicolon (;). When youre done entering values close
the expression with a closing square bracket (]). So if y were a 1 x 2 row vector (1 row,
two columns) you could enter the values as shown below

>> y = [1 2];

Note the semicolon at the end of the line that prevented an echo. To make sure that y
really does contain the proper values all you have to do is just to type y then enter to get

>> y

y =

1 2

>>

To enter a column vector (n rows, 1 column) just separate the entries by semicolons
within the square brackets. So for a 2 x 1 column vector z you would get

>> z = [3;4]

z =

3
4

>>

Note that by not putting the semicolon at the end of the line I did get the echo of the
command that was typed, verifying that z is a 2 x 1 column vector. To get an n x n
matrix (array) simply combine the two procedures. So for w (a 2 x 2 ) array you would
get

>> w = [ 5 6;7 8]

w =

5 6
7 8

>>

Multiplying matrices and vector then is easily done, e.g., multiplying y by z gives

>> y*z


ODE Solvers 7
ans =

11

or multiplying z by y

>> z*y

ans =

3 6
4 8

>>

Finding an inverse of a matrix is also simple

>> w^-1

ans =

-4.0000 3.0000
3.5000 -2.5000

>>

How do you use Matlab to solve ODEs? Like MathCAD, Matlab has a number
of integrators that can be used to solve ODEs. The one that Matlab recommends is
ode45, which is also a Runge-Kutta type integrator. Setting-up to run the integrator in
Matlab is a bit more complex. When you first start-up Matlab you are in the Matlab
Command Window. From this window you can execute many of the functions in Matlab.
However, for the integrator to work you need to create an m-file that will contain the
definitions for all of the derivatives. To do this click on File, then click on New, then
select M-File. This will open a new editing window for you. To solve the example
problem from above I created the following m-file.

f unct i on dC = exampl e( t , C)
dC=zer os( 2, 1) ; %cr eat es a 2x1 vect or
dC( 1) =- 0. 5*C( 1) ; %def i nes t he der i vat i ve f or dCA/ dt
dC( 2) =0. 5*C( 1) - 1. 5*C( 2) ; %def i nes t he der i vat i ve f or dCB/ dt

The vector dC will contain the values for dC
A
/dt and dC
B
/dt. The vector C will contain
C
A
and C
B
. Remember that the semicolon at the end of each line prevents Matlab from
displaying the results for that line on the screen and the % sign allows you to enter
comments. When you have finished creating your m-file for calculating the needed
differentials you then need to save this file. When you click on Save you will be asked
where to save the m-file. Unless you want to go into Matlab and redefine the default path

ODE Solvers 8
just accept the path displayed. After saving the m-file you now may close the editing
window and go back to the command window.

To actually do the integration I used the following commands in the Command Window.


Thi s ver si on i s f or educat i onal cl assr oomuse onl y.

To get st ar t ed, t ype one of t hese: hel pwi n, hel pdesk, or demo.
For pr oduct i nf or mat i on, t ype t our or vi si t www. mat hwor ks. com.

[ t , C] =ode45( ' exampl e' , [ 0: 0. 1: 10] , [ 2 0] ) ; %i nt egr at e f r omt = 0 t o
t = 10 i n st eps of 0. 1 wi t h CAo=2 and CBo=0
C( : , 3) =2- C( : , 1) - C( : , 2) ; %comput e CC f r omt he mat er i al bal ance
pl ot ( t , C( : , 1) , t , C( : , 2) , ' - . ' , t , C( : , 3) , ' - - ' ) %pl ot CA, CB and CC
ver sus t
[ t , C] =ode45( ' exampl e' , [ 0: 1: 10] , [ 2 0] ) ; %i nt egr at e f r omt = 0 t o t
= 10 i n st eps of 1 wi t h CAo=2 and CBo=0
C( : , 3) =2- C( : , 1) - C( : , 2) ; %comput e CC f r omt he mat er i al bal ance
[ t , C]

ans =

0 2. 0000 0 0
1. 0000 1. 2131 0. 3834 0. 4036
2. 0000 0. 7358 0. 3181 0. 9462
3. 0000 0. 4463 0. 2120 1. 3417
4. 0000 0. 2707 0. 1329 1. 5965
5. 0000 0. 1642 0. 0815 1. 7543
6. 0000 0. 0996 0. 0497 1. 8508
7. 0000 0. 0604 0. 0302 1. 9094
8. 0000 0. 0366 0. 0183 1. 9451
9. 0000 0. 0222 0. 0111 1. 9667
10. 0000 0. 0135 0. 0067 1. 9798



A few words of explanation about these steps. The first statement obviously starts the
integrator. The name of the function that defines the differentials needs to be in single
quotes and is the same as the name you assigned to the function you created in the m-file.
The next argument in the call for the integrator, [0:0.1:10], creates a series of values for
the independent variable (t in our case). In this form t starts at a value of 0 and increases
in steps of 0.1 until it reaches 10. The final argument assigns initial values for C
A
and
C
B
, 2 and 0, respectively. The second step calculates CC from the material balance. The
colon in the specification of the matrix tells Matlab to do this operation on all rows in the
matrix. The third line plots the results. The structure of this command is that you need to
specify both the independent variable and the dependent variable for each plot. Since I
wanted all three plots on one set of axes I included all three in a single plot command.
The information in single quotes following the second and third plot specifications cause
the type of line created to change its format. When you hit enter after this line a new
window opens that contains the plot. Well discuss options here in the next paragraph.
To obtain printed results I could have t and C printed, but again, there are usually more

ODE Solvers 9
values generated to get a good looking plot than you want to see in tabular form. I could
have gone back and tried to manipulate C (to eliminate some values) but since it is so
easy to invoke the integrator I simply did the integration again but this time with a larger
increment in t. Remember that you can use the key to scroll through previous
commands. Thus I went back through the commands until I found the original call for
the integrator, then changed the range to [0:1:10] and recomputed. Again I scrolled
through the prior commands to find the line where CC was computed. Finally typing
[t,C] and hitting enter gives the printed results I wanted.

After hitting the plot command the new window that opens contains the following plot.
0 1 2 3 4 5 6 7 8 9 10
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2

Along the menu line at the top is one that has an arrow leaning to the left. Click on this
to enable plot editing. If you now double click somewhere on the figure youll get a
menu window that allows you to enter a title and label the axes. If you click on one of
the lines you can modify the appearance of the line. Finally, if you click on Tools on the
top menu you can select an option for Show Legend. If you double click on the text in
the legend you then can add the text you wish. You also can drag the legend box around
on the figure to get it to the place you want. You should be able to generate a figure that
looks like the figure on the following page.


ODE Solvers 10
0 1 2 3 4 5 6 7 8 9 10
0
0.2
0.4
0.6
0.8
1
1.2
1.4
1.6
1.8
2
t
C
A
,
C
B
,
C
C
Example Problem
CA
CB
CC

Simulink (included in Matlab)

Matlab includes an option called SimuLink that also allows the solution of
ODEs. You can initiate Simulink by clicking on the icon in the menu bar



or by typing simulink at the command line (the line with the >> symbol). This will open
up a new window, the Simulink Library Browser as shown below.


ODE Solvers 11


In the upper left hand corner of the Library Browser click on the new file symbol to
obtain a work space for you model as shown below.




ODE Solvers 12
In the menu in the Library Browser window select Continuous. From the symbols that
appear left-click and hold on the symbol for State-Space and drag it to the work space
to obtain the following



Double-clicking on the symbol in the workspace gives




ODE Solvers 13
Remember that Matlab was designed to work with vectors and matrices. Thus the model
form

u D x C y
u B x A
dt
x d
+ =
+ =


expects A, B, C, and D to be n x n matrices and x, y, and u to be n x 1 column vectors.
This block is called a state-space model since the dependent variables (C
A
, C
B
and C
C
in
our case) are considered to be states for our system. The vector x is the column vector
containing the values of the states for our system, i.e.,

(
(
(

=
C
B
A
C
C
C
x

Thus x(1) = C
A
, x(2) = C
B
and x(3) = C
C
. Our original set of equations then can be
rewritten as

) 2 ( 5 . 1
) 3 (
) 2 ( 5 . 1 ) 1 ( 5 . 0
) 2 (
) 1 ( 5 . 0
) 1 (
x
dt
x d
x x
dt
x d
x
dt
x d
=
=
=


with the initial condition

(
(
(

=
0
0
2
u

since the vector u contains the input conditions (initial values). Rewriting the set of
differential equations in vector/matrix format gives

x A x
dt
x d
=
(
(
(

=
0 5 . 1 0
0 5 . 1 5 . 0
0 0 5 . 0


Where a single underscore represents a vector and a double underscore represents a
matrix. We now can enter the data in the window for the State-Space model
remembering to start the definition of any array with a square bracket ([), separate

ODE Solvers 14
elements in any row by spaces and between columns using a semicolon (;) and end the
definition of the array with a closing square bracket (]).



In Simulink the vector y is the output vector. In the format used in Simulink this is the
result of the integration of the ODEs plus and input values. For this problem we want
only the results of the integration (Later we will be using deviation variables in many
problems where the numerical value we want is the result of integrating the deviation
variable plus its steady-state value). This means that the matrix C that multiplies x
should be the identity matrix, so that the multiplication does not change any values. Thus
the definition of C in the State-Space block is that of the identity matrix (1s on the main
diagonal and zeros in all other positions). The two matrices B and D were both zero
matrices (all elements were 0) since the differential equations and final values did not
include any additive terms. Once you have entered all the values click on Apply, then
OK. Before solving this problem we want someway to see the results. Go to the
Library Browser and click on Commonly Used Blocks. Find Scope and click and
drag the symbol into the workspace. On the righthand side of the State-Space block there
is a connector (the < on the side); on the lefthand side of the Scope that is another
connector (the > on the side). Click on the connector on the State-Space block the drag
until you get the double cross on the connector on the scope. This should give you an
arrow connecting the State-Space to the Scope as shown below.

Now go to the menu bar at the top of the workspace, click on Simulation, then
click on Start in the dropdown menu. Note that in the upper right hand corner there are
two blocks, one saying 10 and the other Normal. The 10 indicates that the simulation
will stop when t = 10. Normal refers to the simulation mode (integrator). These can be
changed to the values you desire (in this case we wanted t = 10 to be the final value so no

ODE Solvers 15
changes are needed). Nothing seems to have changed but if you double click on the
Scope you will get a plot of the results of the integration, shown in the next figure.




Rather than graphical output you may want tabular results. To do this go to the Sinks
label in the Library Browser then click on the To Workspace block and drag it into the
workspace. Double click on the Workspace block and under the variable name enter y
and under the Save Format block enter Array. You will also want to connect this to the
State-Space block but there are no remaining connectors. Place the cursor on the line
between the State-Space block and the Scope. Now hold down the Control key and the
left mouse button and drag to the connector on the Workspace block. This should give
you the following. Now click on Simulation and Start again. Now go to the Matlab main
window and enter y to get the next figure.

ODE Solvers 16





Note that we have obtained the values for all of the concentrations but no values for time.
To get time go to the Sources block in the Library Browser, find Clock, click and drag
the clock into the Simulink workspace. Since we want these values to be available in the
tabular output we also need to connect this to a Workspace block. Go to Sinks, click and
drag another workspace block into the Simulink workspace. Click on the connector for
Clock and drag the cursor to the connector on the Workspace block. Double click on the
Workspace block and enter time the variable name and Array under Save Format. Your
screen should now look like the following.

ODE Solvers 17


Now click on Simulation and Start. Now go back to the main Matlab screen and enter
[time,y]. This will form a new array with the values from time in the first column and the
values from y (C
A
, C
B
, and C
C
) in the following columns. You should see the following
output.




ODE Solvers 18
Note, however, that the time increments are not uniform. This is a result of the
Decimation and Sample Time setting in the two Workspace blocks. The Decimation
value indicates that a value will be printed every nth sample. The default value of 1
outputs the values at every sample time. However, the default integrator in the State-
Space model has a variable step size. The time steps initially are small since the states
are changing rapidly. The time steps get larger towards the end of the simulation since
values do not change as rapidly. The default Sample Time of -1 indicates that it accepts
the sample time from the driving block (State-Space in this case). To get equally spaced
time increments change the value of the Sample time to 0.5 in BOTH workspace blocks
then hit Simulation and Start to get the following.



With the data in the main Matlab workspace we could now use the plot commands as we
did in the earlier section on solving odes in Matlab.

Вам также может понравиться