MATLAB® Applications in Chemical Engineering
MATLAB® Applications in Chemical Engineering
Engineering
James A. Carnell
North Carolina State University
MATLAB is a powerful code -based mathematical and engineering calculation
program. It performs all calculations using matrices and vectors in a logical programming
environment. This guide is a brief introduction to MATLAB in chemical engineering, and
in no way attempts to be a comprehensive MATLAB learning resource. This guide is a
starting point for the new MATLAB user, and as such no prior MATLAB experience is
necessary. Further help can be found in the MATLAB help files or at Mathworks website
at www.mathworks.com and in the help section at
http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.shtml
Table of Contents
Section I: How MATLAB Works
1 Basic MATLAB: The Language
2 Mfiles (Function files)
3 Dealing with Functions
1
file_name is simply the name of the m-file (the filename must be the same in the
definition and the file-name), z is the dependant variable, and x and y are the independent
variables. (Of course, one can have less or more independent variables depending upon
the complexity of the problem and the equations involved.) The next few lines of script in
the m-file can define the function or functions and label any required variables. The
2
following is an example of an m-file used to plot the natural logarithm function.
To produce a plot of this function, the following code is entered into the command
window:
MATLAB uses log as the natural logarithm function, and log10 as logarithm base ten.
Using the insert menu one can add a title, x and y axis titles, and if necessary a legend.
One can also use commands nested within the fplot command to title the chart, add axis
titles, or decide upon curve characteristics such as line color or marker.
Dealing with functions
Standard functions such as the sine, cosine, logarithmic, exponential, and userdefined functions within MATLAB will now be covered. fplot has already been
introduced; now plot, fzero and fsolve will be introduced
The plot function
The plot function produces a 2-D plot of a y-vector versus either its real index or a
specified x-vector. The plot function can be used for data, standard functions, or userdefined functions. Lets look at a simple example of using plot to model data.
Example 1.1
The following reaction data has been obtained from a simple decay reaction:
AB
Use MATLAB to plot the concentration of component A in mol/L against the reaction
time, t, in minutes. Title the plot, label the axes, and obtain elementary statistics for the
data.
MATLAB Applications in Chemical Engineer
James A. Carnell, August 20
Time
(Minutes)
0
1
3
6
9
12
15
18
21
Concentration
(Moles/Liter)
100
80
65
55
49
45
42
41
38
Solution
First, the data must be entered into MATLAB as two vectors. The vectors x and y
are defined in the command window, followed by the command to plot the data. The
following graph is displayed:
The x row matrix (or vector*) has its display output suppressed using the ; at the end
of the line.
Syntax can be used to specify the title and labels, but an easier GUI
(Graphical User Interface) based approach is to simply edit the figure.
1
Select the Edit Plot command found in the Tools menu, or
click the north-west facing arrow icon on the figure.
2 Double click on the white-space in the graph. This enables the property
editor. Now the title and axes can be inserted under the labels command.
3
Now click directly on the line, and the line property editor will
come up. Now the lines color, pattern, or the markers can be edited. The
final curve is presented below:
*A single row matrix or column matrix can represent vectors within MATLAB.
To display simple statistics of the data, follow the path, ToolsData Statistics and the
minimum, maximum, mean, median, standard deviation, and range of x and y will be
displayed. Within this box, each statistic can be added to the curve as a data point/line.
To plot functions using plot, an m-file can be created defining the function, or the
definition can be specified in the command window. This is done in a similar fashion as
seen in fplot. The following code entered into the command window yields a plot of the
exponential function between 0 and 10, at intervals of 1.
There are many other 2-D plotting functions in Matlab, but fplot, plot and ezplot are
the most useful. ezplot is another way to quickly plot functions between specified or
non-specified (-2<x<2) intervals. The syntax key for ezplot is shown below.
Example 1.2
2
Find the zero of the function y(x) = x -1 using an m-file and fzero.
Solution
Create the m-file, myfunction.m
function y =
myfunction(x) y = x^2-1
In the command window, use fzero to find the zero of the function myfunction
x = fzero(myfunction,3)
Matlab returns a few iterations and then produces the result x = 1
Example 1.3
Find the zero of the function y(x) = sin(x) closest to x=3 using the fzero
command directly in the command window. Do not use an m-file for this example.
Solution
Enter into the command window x = fzero(sin(x),3) Matlab returns
a value of 3.1416. This is the zero of sin(x) closest to our initial guess of 3.
Example 1.4
Solve the system of linear equations given below using Matlab.
3.5u + 2v = 5
1
1.5u + 2.8v +1.9w = 1
1
2.5v +3w = 2
Solution
Enter the following code directly into the clear Matlab command window. (If the
window is not clear, enter the command clear to clear the memory of any variables).
The matrix a contains the coefficients of u, v and w respectively. Each row in the matrix
(there are three) corresponds to the coefficients of u, v and w in that order. Matrix b
contains the solution to each row or equation, 5, -1 and 2. The matrix x that is divided
out can be thought of as containing the values for u, v and w.
The solutions to the equations are displayed as u, v and w as they are listed in the matrix.
The command a\b performs reverse matrix division. The command transposes matrix b,
this is required to perform matrix division. It is a property of matrices. Essentially, the
...............................................
f (n) fn (x1 , x2 , x3 ,..., xn ) = 0
Matlabs solver can be used to determine the unknown variables, x1 through xn. The
following example will illustrate the use of the fsolve function.
Example 1.5
Solve the system of equations below using fsolve.
2a b ea = 0
2b a eb = 0
Solution
The most efficient way to solve these types of systems is to create a function mfile that contains the equations.
The equations are separated within the matrix f using the semi-colon operator. Now the
fsolve command must be used to solve the system.
Example 2.1
2
Integrate ax +bx, with respect to x, (where a and b are constant) and then
differentiate the solution obtained with respect to x to regain the initial function.
Solution
To begin with, the symbolic variables within the expression must be defined
within MATLAB as symbolic variables. This is done using the syms command. In the
The syms command is used to define a, b and x as variables for symbolic purposes. The
expression is differentiated to obtain the solution 2ax+b, which upon integration with
2
respect to x yields ax +bx as expected.
MATLAB can solve ordinary differential equations symbolically with or without boundary
conditions or initial value parameters. The dsolve command is used for this purpose. Within
dsolve, the letter Dij is used to indicate a derivative, where i is the order of differentiation,
and j is the dependent variable. D implicitly specifies first order derivative, D2 signifies a
second order derivative and so on. The letter t is the default
d2y
. The following
example dt 2
Example 2.2
Solve the ode
d2y
=6y
dx
dx
dy
Solution
The next example shows how to solve an initial value problem for a second order ode.
Example 2.3
d
d2m
Solve the ode
+ m = 0 , m(0)=2 and m (0) = 3 , where m(x).
2
dx
dx
Solution
Within dsolve, m(0)=2 and Dm(0)=3 define the initial conditions of the ode.
In the assignment of the initial conditions, labeled variables could have been inserted
rather than numeric values. For example, if the initial conditions for example 2.3 were
m(0)=a and
dm
dx (0) = b , then the command chain
could have been used to yield the solution
.
1)
dy
If global variables are used, the global command must be inserted after
the function definition
3)
The ode or odes in the form described above e.g.
The filename, variables (m and t) and dmdt are arbitrary. dmdt is also arbitrary and can
equivalently be called A or any other non-reserved name. One stipulation that exists is
that the definition within the function dmdt=file_name(t,m) MUST be the same as that
defined when the odes are listed. For example, the following function m-file is incorrect
function dmdt=myfile(t,m)
A=4*m
But, the following function file is correct:
function dmdt=myfile(t,m)
dmdt=4*m
(It may appear that from this MATLAB is unable to solve any more than a first order
ode, but all odes of second order or higher can be written in the form of multiple odes,
each of first order. This will be covered once an introduction using first order odes has
been accomplished).
Once a suitable function file has been created, a run-file or executable file is
created that is used to solve the ode or odes that are within the function file. The run file
must contain the following items:
1)
If global variables are used, the global command must be inserted at this
point.
2)
Depending on how the tspan, the integration interval, is defined, the lower
and upper limits can be defined here. E.g.
, where t0 and
tf are predefined vectors for the integration limits. Forward or reverse
integration can be used; t0 does not have to be less than tf in the case of
reverse integration
3)
The initial conditions must be defined as vectors or single
direction matrices.
4)
The ode solver must then be called. The following is the syntax for the
solver, and ode45 is the solver that will be used. It is a good place to start
as a general solver:
5)
The solution can now be plotted using the plot command and then
formatted either using the GUI interface or by the commands legend,
xlabel, ylabel, title and axis. E.g.
,
st
The file ex31run is used to execute the solver. The code for this file is overleaf.
Systems of odes can also be easily solved in MATLAB using the same setup as
described for a single ode. Example 3.2 demonstrated how to solve a system of
simultaneous odes. In example 3.2 the global command is used to define certain
variables as shared or in common between the run file and the function file. Global
variables are not necessary, but they are convenient. Using the global command
variables can be defined once in the run file and the global command will link them to the
function file. If used, the global command must not contain the independent or dependent
variables.
Example 3.2
The following set of differential equations describes the change in concentration
three species in a tank. The reactions ABC occur within the tank. The constants k1,
and k2 describe the reaction rate for AB and BC respectively. The following odes
are obtained:
dCa
dCb
dt = k1Ca
dt = k1Ca k
2Cb
dCc
dt = k 2Cb
-1
Where k1=1 hr and k2=2 hr and at time t=0, Ca=5mol and Cb=Cc=0mol. Solve
the system of equations and plot the change in concentration of each species over
time. Select an appropriate time interval for the integration.
Solution
The following function file and run file are created to obtain the solution:
Ca, Cb and Cc must be defined within the same matrix, and so by calling Ca c(1), Cb c(2)
and Cc as c(3), they are listed as common to matrix c.
Notice that the constants k1 and k2 are defined (only once) in the run file, and using the
global command they are linked to the function file. The following curve is produced
upon execution. In the plot command, the + and * change the line markers so that they
can be easily distinguished using a non-color printer. The appendix contains a list of
available markers for plotting.
dny
= f (x, y, y, y, y,..., y
) dxn
and can also be written as a system of first order differential equations such that
n1
y1 = y, y2 = y, y3 = y,....yn = y n1 .
From here, the system can then be represented as an arrangement such that
y1 = y2 , y2 = y3 ,...yn1 = yn , where y'n=f(x,y1,y2,...yn).
Example 3.3 demonstrates this technique.
Example 3.3
st
To convert this 2 order ode to a system of 1 order odes, the following assignment
is made:
Y = y1 = y(1) and Y = y2 = y(2) ,
then the ode can be written as the first-order system:
Y = y(1)
dY
dt = Y = y(2)
d 2Y
= Y = ( y(2) +
y(1)) dt 2
The function file containing this system can now be created and solved. The function file
and run file are shown below:
The variable dmdt is a dummy variable that is used to describe the system as a whole,
The appendices of this guide are designed to be used as cheat-sheets to aid in using
MATLAB without simply manipulating the examples herein. Successful use of
MATLAB comes from understanding how and why it works the way it does. MATLAB
can be used for almost anything that requires calculation and so frequent use for simple
tasks will aid in the competency of the package.
Appendix
MATLAB Glossary of commands (Part 1)
1 Matrix commands (A is an arbitrary matrix)
1 sum(A)
Summation of the rows of matrix A
A
Transposes matrix A
1 diag(A)
Takes the diagonal values of square matrix A
2 fliplr(A) Flips matrix A from left to right
3 1:n:10 Fills sequence of numbers, 1 to 10 with spacing n (if n is
not stipulated, then MATLAB will assume n=1)
2 Command Window
1 clear Clears memory of variables
2 clc
Clears command window (clf will clear the figure window)
3 Wraps text or code if required, (followed by return or enter)
4 up arrow Recalls last line
;
Output suppression ( eg. Does not SHOW output)
iskeyword Displays reserved MATLAB keywords
1 Functions and other commands
1 plot(independent, dependent) A graphing command.
Independent variables must be defined before using the plot command.
2 fplot(function,[xmin, xmax, ymin, ymax])Graphs a
function either from an m-file or direct command, the function entered
can be a file-name linking to an m-file or it can the the function itself e.g.
sin(x)
3 ezplot(function,[xmin, xmax, ymin, ymax])As
above
4 fsolve(m-file-name,initial_guess,options) Solves
non-linear continuous systems of equations. Initial guess usually in the form
of a matrix, predefined. Usual option is optimset(fsolve)
5 x=fzero(function,initial_guess)Numerically finds the
zero of the function close to the initial guess. The function can be in an mfile or a direct command (similar to fplot). The initial guess can be entered
directly, or in the form of a predefined vector. The in-line function must
be in terms of x only. It cannot contain any predefined constants.
6 m=input(m =)Requests that an input variable be entered into
MATLAB, which is then saved as m or any other arbitrary name. Used
in m-files
7 display(text to be displayed) Displays text to be
displayed in a matlab execution. Used in m-files
In all of the above function definitions, the notation must be included in the MATLAB
3
command execution. For example, the fzero command to find the zero of x , one would
use the notation: x=fzero(x^3,1), where 1 is the initial guess.
Performs
symbolic
differentiation of exp1 with respect to independent variable
independent
4 dsolve(ode1,ode2,oden, bc1,bc2,bcn, IV)
Performs symbolic ode solving, where ode1, ode2 and oden are systems
of odes and bc1, bc2 and bcn are their respective boundary conditions. IV
is the common independent variable. The default IV is t, so if no IV is
specified, then t is assumed to be the independent variable. To indicate a
derivative the capital letter D is used, followed by the order then the
d2y
dependent variable. So D2y represents
. For non-boundary
d (IV )2
condition problems, the bc1,bc2,bc3 term can be negated and the
solution will be returned containing integration constants.
simplify(A) Simplifies expression A
Method
ode45
Runge-Kutta
ode23
Runge-Kutta
ode113
Adams
ode15s
NDFs (BDFs)
ode23s
Rosenbrock
ode23t
ode23tb
TR-BDF2
2. global v1 v2 vi
Defines global variables v1, v2, and vi. When required, the global command is
used in all m files to declare common variables.
3. tspan [to tf]
Sets integration interval. to and tf must be defined prior to
tspan. tspan is an arbitrary name for the row vector containing to and
tf, which are also arbitrarily named.
4. yo=[a0, a1, a2 ]
st
Initial conditions for each dependent variable in a 1 order differential equation.
st
yo is an arbitrary name. A single 1 order DEQ requires only one initial
condition, and each independent DEQ thereafter requires another.
5. [Indepent, dependentbase] = ode#(filename, tspan, y0)
Syntax to instruct MATLAB to use ODE solver called ode# to solve the function
defined in file called filename, using the initial conditions described in y0. # is
the number for a particular solver; generally ode45 works as an initial try.
6. plot (t, y(:,1), t, y(:,2), t, )
Invokes plot command to plot t versus variables defined in function as y(1), y(2),
etc.
7. Plot formatting commands
xlabel(X axis title)
ylabel(Y axis title)
axis([xmin xmax ymin
The operator elseif can also be used. It acts in a similar fashion to the else
command except that it requires a condition to be true. For example, the following
set of differential equations apply to the specified intervals
dm
dt = 4, when m is less than or equal to 10
dm
dt = 2 , when m is between 10 and 20
dm
dt = 6 , when m is greater or equal to 20
In MATLAB, the if, else and elseif commands can be used to specify this
system.
%If this statement is true, then
if m<=10
dmdt=4
%MATLAB executes the ode dmdt=4
elseif m<20
%If the first statement is not true, I.E. we
%are at a point where m is greater than 10,
%then the elseif m<20 dictates that if m is
%less than 20, then dmdt=2, and this is the ode
%MATLAB executes
dmdt=2
elseif 20<=m
dmdt=6
end
%ode dmdt=6
greater than
less than
less than or equal to
greater than or equal to
equals
does not equal
Line Markers
The following table describes the available line markers that can be used for plotting in
MATLAB.
Keyboard key or symbol
+
*
o
.
x
s
d
v
^
>
<
p
h
Marker
Plus sign +
Multiplication sign *
Circle o
Dot .
Cross x
Square
Diamond
Downward pointing triangle
Upward pointing triangle
Right pointing triangle
Left pointing triangle
Five point star
Six point star