Beruflich Dokumente
Kultur Dokumente
Second Class
Part (3)
MATLAB For
Chemical Engineer
3-D graphics
Matlab provides extensive facilities for visualization of three-dimensional data. The
most common are plots of curves in a three-dimensional space, mesh plots and surface
plots. The command plot3(x,y,z,’style option’) produces a curve in the three-dimensional
space. The title, xlabel, ylabel, etc., may be used for three-dimensional plots. The mesh
and surf commands have several optional arguments and are used for plotting meshes and
surfaces.
Following is a list of some specialized 3-D graphs.
plot3 Plot lines and points in 3-D space
mesh 3-D mesh surface
surf 3-D colored surface
ezmesh Easy to use 3-D mesh plotter
ezplot3 Easy to use 3-D parametric curve plotter
ezsurf Easy to use 3-D colored surface plotter
cylinder Generate cylinder
sphere Generate sphere
0
1
1
0 0
y -1 -1 x
96
5
x 10
Example:
t=.01:.01:20*pi; 2
x=cos(t);
y=sin(t);
1
z=t.^3;
plot3(x,y,z)
0
1
1
0 0
Example: -1 -1
t=-5:.005:5;
x=(1+t.^2).*sin(20*t); 5
y=(1+t.^2).*cos(20*t);
z=t; z(t)
plot3(x,y,z) 0
grid on
xlabel('x(t)') -5
ylabel('y(t)') 50
zlabel('z(t)') 50
0 0
y(t) -50 -50 x(t)
Creating 3-D Graphs
MATLAB defines a surface by the z-coordinates of points above a rectangular grid in
the x-y plane. The plot is formed by joining adjacent points with straight lines. Surface
plots are useful for visualizing matrices that are too large to display in numerical form and
for graphing functions of two variables.
mesh: A mesh surface is defined by the z coordinates of points above a rectangular
grid in the x-y plane. The plot is formed by joining adjacent points with straight lines.
Example: Generate the matrix table of the function f=x.^2+y.^2; where 0 <= x <= 5,
0 <= y <= 5
xv=[-5:.1:5];
yv=[-5:.1:5];
nx=length(xv); 40
ny=length(yv);
for i=1:nx 20
for j=1:ny
zmat(i,j)=(xv(j).^2+yv(i).^2); 0
5
end 5
end 0 0
To display the function, we can use mesh function. -5 -5
mesh(xv,yv,zmat);
97
meshgrid
To generate the matrix table, we needed to perform a double nested loop which is
time consuming. MATLAB has it's own method of generating matrix tables using the
meshgrid function.
To see what meshgrid does
x=[6:1:10];
y=[1:1:5];
[X,Y]=meshgrid(x,y);
X=
6 7 8 9 10
6 7 8 9 10
6 7 8 9 10
6 7 8 9 10
6 7 8 9 10
Y=
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
X is a matrix in which the x domain [6 7 8 9 10] is copied in every row and Y is a
matrix in which the y domain [1 2 3 4 5] is copied in every column.
Now since Z(i,j)=Z(x(j),y(i)) by definition and since X(i,j)=x(j) for any i and
Y(i,j)=y(i) for any j, Z(i,j)=Z(X(i,j),Y(i,j)) which is the definition of a matrix array
operation.
For example, meshgrid can be used to generate X- and Y-grid matrices for use
when computing the displayed Z matrix.
x=[0:.1:5];
y=[0:.1:5];
[X,Y]=meshgrid(x,y);
Z=(X.^2)+(Y.^2); 40
mesh(x,y,Z)
20
0
5 5
0 0
98
Example:
x=linspace(-2, 2, 25); 0.5
y=linspace(-2, 2, 25);
[xx,yy]=meshgrid(x, y);
zz=xx.*exp(-xx.^2-yy.^2); 0
mesh(xx, yy, zz);
-0.5
2
2
0 0
-2 -2
-0.5
10
10
0 0
-10 -10
surf: produces a solid filled surface plot.
A surface plot is similar to a mesh plot except the rectangular faces of the surface are
colored.
Example:
x=linspace(-2, 2, 25);
y=linspace(-2, 2, 25); 0.5
[xx,yy]=meshgrid(x, y);
zz=xx.*exp(-xx.^2-yy.^2);
surf(xx, yy, zz); 0
-0.5
2
2
0 0
-2 -2
99
Example:
[X,Y] = meshgrid(-8:.5:8); 1
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R; 0.5
surf(X,Y,Z)
0
-0.5
10
10
0 0
-10 -10
-20
4
2 4
0 2
-2 0
-2
-4 -4
Example:
x=0:pi/20:pi*3; 1
r=5+cos(x);
[a,b,c]=cylinder(r,30);
mesh(a,b,c) 0.5
0
10
10
0 0
-10 -10
100
Example:
t=0:pi/12:3*pi; 1
r=abs(exp(-0.25*t).*sin(t));
[X,Y,Z]=cylinder(r,30);
mesh(X,Y,Z) 0.5
0
1
1
0 0
-1 -1
Example:
t=0:pi/12:3*pi;
r=abs(exp(-0.25*t).*sin(t)); 1
[X,Y,Z]=cylinder(r,30);
surf(X,Y,Z)
0.5
0
1
1
0 0
-1 -1
Example:
[a,b,c]=sphere(40); 1
surf(a,b,c);
0
-1
1
1
0 0
-1 -1
101
ezplot3 (FunX,FunY,FunZ) plots the spatial curve FunX(T), FunY(T), and
FunZ(T) over the default domain 0 < T < 2*Pi.
ezplot3 (FunX,FunY,FunZ,[Tmin,Tmax]) plots the curve FunX(T), FunY(T),
and FunZ(T) over Tmin < T < Tmax.
Example:
ezplot3('cos(2*pi*t)', 'sin(2*pi*t)', 't', [0, 6])
x = cos(2 t), y = sin(2 t), z = t
z
2
0
1
1
0 0
y -1 -1 x
x exp(-x2-y2)
ezsurf('x*exp(-x^2-y^2)')
0.5
-0.5
2
0 2
0
-2 -2
y x
102
Exercise 1:
1
The volume of a right circular cone of radius and height is given by V r 2 h
3
Plot the volume of the cone as and vary on the radius and height.
Solution:
Volume of Right Circular Cone
[R,H]=meshgrid(0: 4, 0: 6);
V=(pi .* R .^ 2 .* H) ./ 3;
mesh(R, H, V)
xlabel('radius r (m)'); 100
volume (m3)
ylabel('altitude h (m)');
zlabel('volume (m3)'); 50
title('Volume of Right
Circular Cone'); 0
5 4
2
altitude h (m) 0 0
radius r (m)
The three−dimensional plot of Figure above shows how the volume of the cone
increases as the radius and height are increased.
Exercise 2:
We would like to plot a surface for the rate of reaction of methane oxidation. The
reaction rate is represented power law R = k r c0.6 2.4
CH4 cO2 , where k is the reaction rate constant
k r 2.610-3
The concentration of O2 in the range between 1 to 10 mols/m3, where the Methane
concentration in the range 40 to 90 mols/m. Taken 10 point of each component plot a
surface for the reaction rate.
Solution
kr=2.6e-3; 10
X1=linspace(40,90,10);
Reaction rate
X2=linspace(1,10,10);
5
[Xch4,Xo2]=meshgrid(X1,X2);
R=kr*(Xch4.^0.6).*(Xo2.^2.4);
Surf(Xch4,Xo2,R); 0
xlabel('O2 conc. mols/m3') 10
103
Practice Problems
1) Create surface plots for the functions
z = (x – 2)2 + 2xy + y2
z = x2 – 2xy + 4y2
z = -x2 + 2xy + 3y2
z = (x –y2) ( x – 3y2)
2) For gases, the pressure is given by the van der Wall’s equation of state,
8 t 3
p 2
3v1 v
3
Plot this equation in three dimensional graph over the range 0.8 t 1.2 and v = 0.5,
0.6, 0.7, 0.8, 0.9, 1.0.
104
Input and Output Options
Matlab offers a number of methods of entering or display data, both on the screen or
for submission. Effective presentation of your results is an important step in any problem
or project. This tutorial will cover input and output options other than the default settings
in Matlab.
You can use MATLAB command named input for input numbers and texts at any
time. This command will display a text string, specified by you, and then wait for input.
Be sure to tell the user how to enter the data, especially if it is to be entered as an array.
>> time = input('Make an initial guess for the time in seconds time = ')
Make an initial guess for the time in seconds time = 32
time =
32
>> disp(5)
5
>> x = 1:3; disp(x)
123
>> y = 3-x; disp([x; y])
123
210
>> disp([x y])
123210
105
M-files
In MATLAB you write programs in M-files. M-files are ordinary ASCII text files
written in MATLAB language. They are called M-files because they must have a ‘.m’
extension at the end of their name. M-files can be created using any editor or word-
processing application. However, MATLAB has a built-in M-file editor which can be
accessed through the Main Menu by
Files > New> M-file
There are two types of M-files – Script files and function files. We now discuss their
purpose and syntax.
Script Files
A script file is an M-file with a set of valid MATLAB commands in it. A script file is
executed by typing the name of the file on the command line. This is equivalent to typing
all the commands in the script file one-by-one. Script files work on global variables, that
is, variables currently present in the workspace. Results obtained from executing a script
file are left in the workspace.
Example
We will write a script file to solve the following system of equations.
5 2r r x1 2
3 6
2r 1 x2 3
2 r 1 3r x3 5
or Ax = B.
Clearly, A depends on the parameter r, and we want to find the solution of the
equations for various values of the parameter r. We will write a script file to do this and
call it solvex.m which we will save in our workspace.
This error arises because we have not defined the variable r. So first we must put r
into the workspace and then execute the above script file again.
106
>> r = 1;
>> solvex;
The results will be
x=
-0.0312
0.2344
1.6875
Note that the value of r is specified outside the script file. All variables in the
workspace are available for use within script files, and all variables in the script file are
left in the work space. Check this. So if you want to do a big set of operations but in the
end you only want a few outputs, then a script file is not the correct choice. In this case
you should use a function file.
Function files
An M-file that contains the word function at the beginning of the first line is a
function file. A function differs from a script in that arguments may be passed, and
variables defined and manipulated inside the file are local to the function and don’t operate
globally on the workspace.
By means of function files we can add new functions to Matlab. A function file
contains a sequence of commands, like a script file, but by means of input and output
variables it is possible to communicate with other files.
Globally a function file has the following form:
function output_variable = function_name(input_variable)
commands
The word function in the first line indicates it is not a script file.
Remark: At function_name you need to fill in the file name without the extension .m .
Both the input variable as well as the output variable may be vectors.
107
For example:
function y = ratio(v);
% This function computes the ratio of the elements of vector v.
y = v/sum(v);
Variables used in a function file are local (i.e. only accessible inside the function),
and therefore they are not stored in the Matlab memory.
function y = comp(x);
a = 2; % the variable a has the value 2, but only within this function
y = a * x;
Often it is necessary to use a variable in a function that gets its value outside the
function. You can show Matlab you want to use such a variable by adding it to the list of
parameters of that function. In the following example we add the variable a to the list of
parameters of the function comp:
function y = comp(x,a);
y = a * x; % the variable a gets its value outside the function and is
% given to the function
Remark: The declaration with global should only be used when there is no other
possibility.
Example
We will now write a function to solve the system of equations defined above. We
give the function a value of r as input and x will be output. We will call this function
solvexf.m
function [x]=solvexf(r);
A = [5 2*r r; 3 6 2*r-1; 2 r-1 3*r]; % create the matrix A
b = [2; 3; 5]; % create the vector b
x = A\b; % solve for x
108
Now r and x are all local variables. Any other variable names can be used in their
place in the function call statement. Sample output would be as follows:
[y] = solvexf(1)
The result will be as below
y=
-0.0312
0.2344
1.6875
The only variables left in the workspace after execution will be the variables in the
workspace.
Let’s create a m-function which when passed an x value, returns the value of
f(x) x 3 x 2 3x 3 0 . In the MatLab editor, open a new page and type the following:
Now save this as f1. Matlab will automatically add the .m extension
To call this m-function at the command prompt, for example to find the value of f(9),
and assign to a variable z, we type :-
>> z=f1(9)
z=
780
>> z=f1(-1:.5:1)
z=
0 -1.3750 -3.0000 -4.1250 -4.0000
Of course, Matlab m-functions can have multiple arguments and multiple return
values, e.g.
Notes
a) function[u,v,w] = yourfun (x,y);% For 3 outputs u, v, w and 2 inputs x, y
b) function[W]= myfun(x,y,z);%For 1 output W and three inputs x, y, z
OR equivalently
function W = myfun(x,y,z)
c) [A,B,C] = yourfun(-5,4)
109
This means that input values are x=-5, y=4, and output values for A, B, and C, are
calculated according to the function prescription
d) [M] = myfun(2,4,-3)
OR equivalently
M = myfun(2,4,-3)
Example
(a) Write a function that performs an ideal gas calculation, where the function is
called as follows:
IdealGas(P,V,T,R), and returns the value of n, the number of moles.
function n = IdealGas(P,V,T,R)
n = P*V/R/T;
(b) Apply the function in the command window to calculate the number of moles that
exist in a volume of 22.4 L, at a pressure of 1 atm, and at a temperature of 273 K.
>> IdealGas(1,22.4,273,0.082)
ans =
1.0006
(c) Write a script file IG_main.m that performs the ideal gas calculation to determine
number of moles. The script should ask the user for each of the other four quantities.
function [P]=pressure(V,n,T)
R=0.082 ;% [L atm/K mol]
P=n*R*T/V;
110
Example
The quadratic equation provides the roots to the polynomial ax 2+bx+c=0 according
- b b 2 4ac
to: x
2a
Write a function called qe(a,b,c), that solves the quadratic equation and returns
solutions. Use your function to solve for the roots of the equation x 2 + 6x – 91 = 0.
>> [x1,x2]=qe(1,6,-91)
x1 = 7
x2 = -13
Example
Function for calculating enthalpy depending on entering temperature, reference
temperature and vector of specific heat equation constants.
function dH = deltaH_IG(Ti,Tf,Cp)
dH = Cp(1)*(Tf-Ti)+Cp(2)*(Tf^2-Ti^2)/2+Cp(3)*(Tf^3-Ti^3)/3+Cp(4)*(Tf^4-Ti^4)/4;
Example
Vapor Pressure for a given Temperature ln P = A - B/(T+C)
Input: Antoine Constants (A,B,C), T
Output: Vapor Pressure
A, B, C constants of Antoine equation.
function vp = sat_pr_antoine(A, B, C, T)
vp = exp(A - B./(T+C));
Example
Heat capacity of air in J/(mol K), where T is in K. The equation is valid only in the
range 273 K < T < 1800 K the file is called as Cp = CpAir(T)
function Cp = CpAir(T)
if T < 273
disp('Temperature too low')
elseif T > 1800
disp('Temperature too high')
else
Cp = 28.09 + 0.1965e-2*T + 0.4799e-5*T^2 - 1.965e-9*T^3;
end
111
Example
MATLAB M-function developed for the pressure-explicit van der Waals equation.
This M-function calculates pressure according to the van der Waals equation of state
RT a
P 2
V b V
The code shown below must be saved in a file with the following name:
VdWEOS_P.m
Note: functions can be saved as separate files and called from any program or
embedded into other functions and used from the main function only. In the latter case
specify the main program as a function.
Global Variables
If you want more than one function to share a single copy of a variable, simply
declare the variable as global in all the functions. Do the same thing at the command line if
you want the base workspace to access the variable. The global declaration must occur
before the variable is actually used in a function. Although it is not required, using capital
letters for the names of global variables helps distinguish them from other variables. For
example, create a new function in a file called falling.m:
function h = falling(t)
global GRAVITY
h = 1/2*GRAVITY*t.^2;
global GRAVITY
GRAVITY = 32;
y = falling((0:.1:5)')
The two global statements make the value assigned to GRAVITY at the command
prompt available inside the function. You can then modify GRAVITY interactively and
obtain new solutions without editing any files.
112
Saving Your Work
When using MATLAB, you will frequently wish to end your session and return to it
later. Using the save command, you can save all of the variables in the MATLAB
workspace to a file. The variables are stored efficiently in a binary format to a file with a
".mat" extension. The next time you start MATLAB, you can load the data using the load
command. See "help save" and "help load" for details.
If you want to save all your variables and their current values, type:
Before you exit MATLAB, and your work will be saved in a file named filename.mat
(default filename matlab.mat). If you only want to save some of the variables, you can
give the save command the names of the variables to save. If you type:
MATLAB will save just the variables x and y in the file filename.mat.
When you start up MATLAB at some future time, you can restore all your variables
from the file filename.mat by typing:
The command load, by itself, loads all the variables saved in matlab.mat.
A file with the extension .mat is assumed to be binary MATLAB format. To retrieve
the variables from filename.mat, the command is:
>>load filename
Example
>> x=1:1:10
x=
1 2 3 4 5 6 7 8 9 10
>> y=2:2:20
y=
2 4 6 8 10 12 14 16 18 20
113
>> z=x.*y
z=
2 8 18 32 50 72 98 128 162 200
>> save data
All existed data in the workspace will saved in the data name
114
Numerical Solution of Differential Equations
xi xi -1 hf (ti -1 , xi -1 )
The right hand term includes the value of the function f at the next step (t+h) and x
(t+h). The unknown x (t+h) appears then in both sides of the equation. The evaluation of x
(t+h) requires the solution in general of a nonlinear algebraic equation which may be a
tedious task.
Exercise 1: Simple first order ODE
Consider the following initial value problem:
dx
t2 t With the initial condition: x (0) = 0.5
dt
Solution:
t_in=0;t_fin=2;nsteps=10;
dt=(t_fin-t_in)/nsteps;
t(1)=t_in; x(1)= 0.5;
for n=1:nsteps
t(n+1)=t(n)+dt
x(n+1)=x(n)+dt*(t(n)^2+t(n))
end
plot(t,x),xlabel('Time (t)'),ylabel('x(t)')
115
The result is in Figure (1)
4.5
3.5
x(t)
2.5
1.5
0.5
0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2
Time (t)
That is
x(0.2) 0.5 0 0.5
The calculations results are plotted in Figure 2 showing the true and the approximate
value for h=0.2. Although the general trend of the true and the approximate values is the
same, the error is large. One way to reduce this error is by choosing a smaller step size.
Figure 2 shows the solution when the step size is halved i.e. h=0.1. Since the Euler's
method is first order, the global error is halved O (h /2) while the local error is quartered O
(h2/4). To get acceptable levels of errors the step size has to be further reduced to very low
values. This will however considerably increase the computational time since it will take a
larger number of iterations for each step. Nevertheless the Euler's method because of its
simplicity and easiness for implementation is still attractive for many engineering
problems.
116
5.5
4.5
x(t) 3.5
2.5
0.5
0 0.5 1 1.5 2 2.5
Time (t)
In order to solve a particular differential equation, we need to define the step size dt
from the initial and final t values t_in and t_fin, and the number of steps nsteps.
The solution is returned in an array h.
t_in=0; t_fin=5;
nsteps=10;
dt=(t_fin-t_in)/nsteps;
h0=2.5; t(1)=t_in;
h(1)=h0;
for n=1:nsteps
t(n+1)=t(n)+dt
h(n+1)=h(n)+dt*(0.5-h(n)^0.75)
end
plot(t,h,'k-'),xlabel('t'),ylabel('h')
117
2.5
1.5
h(t) 1
0.5
0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Time(t)
With the initial condition that y0 is known at x0. The problem of integrating a first-
order ODE is often called an “initial value problem.” In all equations below, h is the
integration step size,
h xi 1 xi .
118
The algorithm for 4th-order Runge-Kutta integration of single ODE is:
h xi 1 xi
h
yi 1 yi (k1 2k 2 2k 3 k 4 )
6
Where:
k1 f ( x i , y i )
h h
k 2 f ( xi , y i k1 )
2 2
h h
k 3 f ( xi , y i k 2 )
2 2
k 4 f ( xi h, y i k 3 h)
Consider the following system of first-order ODE’s describing the dependence of two
dependent variables y and z on one independent variable x:
dy
f(x,y,z)
dx
dz
g(x, y,z)
dx
These two differential equations are coupled and must be integrated simultaneously
because both equations involve both dependent variables.
Initial conditions are required giving the values of y and z at the initial value of x.
The algorithm for 4th-order Runge-Kutta integration of two coupled ODEs is:
119
From the one and two ODE examples, you can extend the method to integration of
three coupled ODE’s. Three coupled ODE’s would be encountered, for example, for
reaction of gases in a steady-state non-isothermal plug flow reactor with significant
pressure drop (dC/dx =, dT/dx =, and dP/dx=).
0 0.5 1 1.5 2
Time (t)
dx
Figure (4): analytical and Runge-Kutta integration for t 2 t function
dt
120
MATLAB Built-In Routines for solving ODES
To solve the same example using MATLAB Routine, We just have to write a
function which returns the rate of change of the vector x.
function dx = example(t,x)
dx(1,1) = t^2+t;
The above file named example.m must be saved in default MATLAB folder then the
following code must run.
t_in=0;t_fin=2; nsteps=10;
dt=(t_fin-t_in)/nsteps;
Vspan = t_in:dt:t_fin;
x0=0.5;
[t,x] = ode45('example',Vspan,x0);
plot (t,x,'k*:')
xlabel('Time (t)'),ylabel('x(t)')
legend('Runge Kutta integration')
The numerical solution, computed using ODE45 is given below in Figure (5)
4
x(t)
0 0.5 1 1.5 2
Time (t)
121
Exercise 4:
Let’s consider a simple example of a model of a plug flow reactor that is described by
a system of ordinary differential equations. A plug flow reactor is operated as shown in
Figure (6) below.
A
k1
B
k2
C
The plug flow initially has only reactant A, the components A react to form
component B. The mole balance for each component is given by the following differential
equations
dCA
u k1C A
dz
dC
u B k1C A k2CB
dz
dC
u C k 2C B
dz
If u=0.5 m/s and reactor length z=3 m. Solve the differential equations and plot the
concentration of each species along the reactor length
Solution:
We’ll start by writing the function defining the right hand side (RHS) of the ODEs.
The following function file ‘example2’ is used to set up the ode solver.
function dC= Exercise4 ( z, C)
u = 0.5;k1=2; k2=3;
dC(1,1) = -k1 *C(1) / u;
dC(2,1) = (k1 *C(1)-k2 *C(2)) / u;
dC(3,1) = k2 *C(2)/ u;
122
Now we’ll write a main script file to call ode45. CA, CB and CC must be defined
within the same matrix, and so by calling CA as C(1), CB as C(2) and CC as c(3), they are
listed as common to matrix C.
The following run file is created to obtain the solution:
clear all, clc
C0 = [1 0 0];
txspan = [0 3];
[z , C] = ode45('Exercise4', txspan, C0)
plot (z,C(:,1),'k+-',z,C(:,2),'k*:',z,C(:,3),'kd-.')
xlabel ('Length (m)');
ylabel ('Concentrations (kmol/m^3) ');
legend ('A', 'B', 'C');
1
A
B
Concentrations (kmol/m3)
0.8
C
0.6
0.4
0.2
0
0 1 2 3
Length (m)
Figure (7): A, B and C concentrations along plug flow reactor
Practice Problems
1) A ball initially at 1200 K is allowed to cool down in air at an ambient temperature.
Assuming heat is lost only due to radiation, the differential equation for the
temperature of the ball is given by
dT
2.2067 10 -12 ( T 4 81 10 8 )
dt
Where T is in K and t in seconds.
Plot the temperature at time range 0 t 480 seconds using fourth order Runge-
Kutta ode45 method.
123
2) The concentration of salt x in a homemade soap maker is given as a function of
time by
dx
37.5 3.5 x
dt
At the initial time, t 0 , the salt concentration in the tank is 50 g/L.
Using Runge-Kutta 4th order method and a step size of, h 1.5 min , what is the salt
concentration after 3 minutes (compare the numerical integration result with exact
solution result)?
3) Consider two interacting tanks in series, shown in Figure (8) with outlet flow rates
that are a function of the square root of tank height. Notice that the flow from
tank 1 is a function of h 1 h 2, while the flow rate out of tank 2 is a function of
h2 .
F
h1 h2
F1 F2
Tank 1 Tank 2
Figure (8): Interacting tanks.
124
Ordinary Differential Equation
dx
f ( x, t ) with x(0) x0 (1)
dt
On the left hand side is the derivative of the dependent variable x with respect to the
independent variable t. On the right hand side, there is a function that may depend on both
x and t. The independent variable t often represents time. In contrast to discrete time
equations of the form xt 1 f ( xt ) , where time t is discrete ( t 1, 2,... ), the independent
variable t in Equation (1) is a continuous variable, that is, it takes on real values, for
instance, t . In addition, we prescribe the initial value at time 0, namely x0. (The
initial condition could be stated for some other time but time 0 is quite commonly used). A
differential equation is called ordinary if it involves only one independent variable.
Many differential equations cannot be solved exactly. Numerical methods have been
developed to approximate solutions. Numerical analysis is a field in mathematics that is
concerned with developing approximate numerical methods and assessing their accuracy,
for instance for solving differential equations. We will discuss the most basic method such
Taylor and Euler methods.
1 2 1 1
y( x h ) y( x ) hy( x ) h y( x ) h3 y( x ) h4 y( 4 ) ( x ) (2)
2! 3! 4!
Solution:
The higher order derivatives are:
y' ' ( x ) 1 y' y' ' ( 0 ) 1 1 2
y' ' ' ( x ) y' ' y' ' ' ( 0 ) 2
y' ' ' ' ( x ) y' ' ' y' ' ' ' ( 0 ) 2
etc
To find the exact solution try the code
125
y=dsolve('Dy=t+y','y(0)=1')
This gives
y=
-1-t+2*exp(t)
This means that the solution of above equation is
y - 1 - x 2 * exp(x)
Now to find the numerical solution, rewrite equation (3) for the following example
using MATLAB program code
Note: increasing the number of j in the inner loop will increase the accuracy of
predicted y
126
2. Euler’s Method
Exercise 2:
Apply Euler’s method to approximate the solution of the initial value problem
dy
2y with y (0) 5 (5)
dx
We know what the solution of equation (5) is, namely y 5 exp(2 x) . We numerically
solve equation (5) using Euler’s method with h=0.1 in the time interval [0, 0.5], and then
check how well this method performs. We have f ( y) 2 y . Then
x0 0
x1 x 0 h 0 0.1 0.1
x 2 x1 h 0.1 0.1 0.2
x 3 x 2 h 0 .2 0 . 1 0 .3
x 4 x 3 h 0 .3 0 .1 0 .4
x 5 x 4 h 0 .4 0 .1 0 . 5
And
y0 5
y1 y 0 hf ( y 0 ) 5 (
0.1)(2)(5) 6
h f ( y0 )
y 2 y1 hf ( y1 ) 6 (0.1)(2)(6) 7.2
y 3 y 2 hf ( y 2 ) 7.2 (0.1)(2)(7.2) 8.64
y 4 y 3 hf ( y 3 ) 8.64 (0.1)(2)(8.64) 10.368
y 5 y 4 hf ( y 4 ) 10.368 (0.1)(2)(10.368) 12.4416
127
x y Exact Difference
0 5 5 0
0.1 6 6.107014 0.107014
0.2 7.2 7.459123 0.259123
0.3 8.64 9.110594 0.470594
0.4 10.368 11.1277 0.759705
0.5 12.4416 13.59141 1.149809
The third column contains the exact values, y 5 exp(2 x) . The last error contains the
absolute error after each step, computed as |y-Exact|. We see that when h=0.1, the
numerical approximation is not very good after five steps. If we repeat the same
approximation with a smaller value for h, say h=0.01, the following table results for the
first five steps:
X y Exact Difference
0 5 5 0
0.01 5.1 5.101007 0.001007
0.02 5.202 5.204054 0.002054
0.03 5.30604 5.309183 0.003143
0.04 5.412161 5.416435 0.004275
0.05 5.520404 5.525855 0.005451
Doing five steps only gets us to x=0.05. We can do more steps until we reach x=0.5.
We find that the final point will be:
X y Exact Difference
0.5 13.45794 13.59141 0.133469
Choosing a smaller value for h resulted in a better approximation at x=0.5 but also
required more steps. One source of error in the approximation comes from the
approximation itself. Another source comes from rounding errors when we implement the
approximation on a computer. It is therefore not necessarily the case that smaller values of
h always improve the approximation.
3. Runge-Kutta Method
dy
To find numerical solution to the initial value problem f ( x, y ), y (0) y 0 using
dx
Runge-Kutta method we have the following consideration (This method gives more
accurate result compared to Euler’s method):
k1 f ( x n , y n )
k 2 f ( x n h / 2, y n hk1 / 2)
k 3 f ( x n h / 2, y n hk2 / 2)
k 4 f ( x n 1 , y n hk3 )
h
y n 1 y n ( k1 2 k 2 2 k 3 k 4 )
6
128
Exercise 4:
Solve the following equation using both Eular and Runge-Kutta method and to
dy
approximate the solution of the initial value problem x y, y (0) 1 with step size h =
dx
0.1.
Solution:
Eular Runge Kutta
clear all, clc,format short clear all, clc,format short
x(1)=0; x(1)=0;
y(1)=1; y(1)=1;
h=0.5 h=0.1;
for i=1:5 f=inline('x+y');
x(i+1)=x(i)+h; % f(x,y) = x+y
dy=x(i)+y(i); for i=1:5
y(i+1)=y(1)+h*dy; x(i+1)=x(i)+h;
end k1 = f(x(i),y(i));
y_exact= -1-x+2*exp(x); k2 = f(x(i)+h/2,y(i)+k1*h/2);
error=y_exact-y k3 = f( x(i) + h/2,y(i)+k2*h/2);
table=[x',y',y_exact',error'] k4 = f( x(i) + h,y(i)+k3*h);
y(i+1)=y(i)+(1/6)*h*(k1 +2*k2 + 2*k3 +k4);
end
y_exact= -1-x+2*exp(x);
error=y_exact-y
table=[x',y',y_exact',error']
table = table =
0 1.0000 1.0000 0 0 1.0000 1.0000 0
0.1000 1.1000 1.1103 0.0103 0.1000 1.1103 1.1103 0.0000
0.2000 1.1200 1.2428 0.1228 0.2000 1.2428 1.2428 0.0000
0.3000 1.1320 1.3997 0.2677 0.3000 1.3997 1.3997 0.0000
0.4000 1.1432 1.5836 0.4404 0.4000 1.5836 1.5836 0.0000
0.5000 1.1543 1.7974 0.6431 0.5000 1.7974 1.7974 0.0000
Note: compare the results of both two methods (Eular and Runge Kutta) with the
results of modified Eular method that supported in Exercise 3.
To be able to solve higher order ode’s in MATLAB, they must be written in terms of
a system of first order ordinary differential equations. An ordinary differential equation
can be written in the form:
dny
n
f ( x , y , y' , y' ' , y' ' ' ,.....,y n 1 )
dx
it can also be written as a system of first order differential equations such that
y1 y , y2 y' , y3 y' ' ,......yn y n 1
This system of equations can then be represented as an arrangement such that
y'1 y2 , y'2 y3 ,........y'n 1 yn ,where y'n f(x,y1 ,y2 ,...yn ).
129
Exercise 5: Solve the following differential equation by converting it to a system of
first order differential equations, then using a numeric solver to solve the system. Plot the
results. T' ' T' T 0, T(0) 1 and T' (0) 0
To convert this 2 order ode to a system of 1st order ode’s, the following assignment
nd
function dydt=example5(t,y)
dydt(1,1)=y(2);
dydt(2,1)=-(y(2)-y(1));
And run file are shown below:
clear all,clc
tspan=[0 10]
To=[1 0]
[t,T]=ode45('example5',tspan,To)
plot(t,T(:,1),'k-+',t,T(:,2),'k:*')
legend('T','dTdt'), xlabel('t'), ylabel('T and dT/dt')
The following curve is produced
350
T
300
dTdt
250
T and dT/dt
200
150
100
50
0
0 2 4 6 8 10
t
Figure (1) Solution of 2nd order differential equation using runge-kutta integration method
Note: the exact solution of higher order ordinary nonlinear differential equations can be
found by dsolve command.
130
Non-Linear Equation Solving
MATLABs built-in function: (fsolve)
Syntax
x = fsolve(fun,x0)
Description
x = fsolve(fun,x0) starts at x0 and tries to solve the equations described in fun. You
need to define your equation in a function file.
Exercise 1:
Given that the vapor pressure of methyl chloride at 60 oC is 13.76 bar, use the
Redlich-kwong equation to calculate the molar volume of saturated vapor at these
conditions. Where Redlich-kwong equation is given as follows:
RT a
P 1/ 2
V b T V (V b )
Where:
0.42748R 2Tc2.5 RTc
a and b
pc 8 pc
The variables are defined as:
P = pressure in bar
V = molar volume in cm3/mol
T = temperature in K
R = gas constant (83.14 = bar.cm3/mol.K)
Tc = critical temperature in K
Pc = critical pressure in bar
Knowing: Pc=66.8 bar, Tc=416.3 oK
Since the above equation is nonlinear in the molar volume (V), it can be solved by a
proper numerical technique.
Write MATLAB code to solve this exercise using fsolve method:
131
Function file named EX
function F= EX(V)
global R T P a b
F = (R*T)/(V-b)-a/(T^.5*V*(V+b))-P;
The above code will find the value of the variable V which makes the function F
equal to zero. The results will be:-
132
Homework
1) Solve the following ordinary differential equation initial value problems for y(x):
y”+y’-6y=0, y(0)=0, y’(0)=1
And compare your results with the exact solution:
y=(1/5)e2x-(1/5)e-3x
2) Solve the following ordinary differential equation initial value problems for y(x):
y”+3y= e x , y(0)=1, y’(0)=1
And compare your results with the exact solution:
3
y=(3/4)cos( 3x )+ sin( 3x )+(1/4)e-x
4
3) Given
d2y
2 y e t , y 0 1, 0 2
dy dy
2
dt dt dt
Find y0.75 by using Fourth order Runge-Kutta
4) Plot y with respect to x in the range 0<x< 10 for the following system of
equations:-
d2y dy dy
2
2 y 0, (0) 2, y (0) 4 ,
dx dx dx
d3y d2y dy d2y dy
3
3 2
5 y sin x , 2
(0) 12, (0) 2 , y (0) 4
dx dx dx dx dx
Solve the set of equations with initial conditions x(0) = 2 and y(0) = 2 over the time
interval 0 t 20. Plot x vs t and y vs t in two different figures. Use hold on to keep the
plots and graphs of subsequent solutions as overlay plots.
133
Solved problems
By neglecting the negative and imaginary roots, the correct answer is the first root
T=1175.1599
Solution 2:
T=0:1:10000;
Cp=0.99403+1.617e-4*T+9.7215e-8*T.^2-9.5838e-11*T.^3+1.9520e-14*T.^4;
Ti=interp1(Cp,T,1.2)
Gives the result
Ti =
1.1752e+003
134
∫
Q 3:The average values of a specific heat can be determined by Cpmh =
Use this relationship to verity the average value of specific heat of dry air in the range
from 300 K to 450 K, Cp KJ/(Kg K), to temperature (K):
Cp= 0.99403 +1.617×10-4T+9.7215×10-8T2 – 9.5838 × 10-11 T3 + 1.9520 × 10-14 T4
Solution:
syms T
Cp=0.99403+1.617e-4*T+9.7215e-8*T.^2-9.5838e-11*T.^3+1.9520e-4*T.^4;
Cpmh=single((int(Cp,300,450))/(450-300))
Solution 1
MW=[16 2 32 28 44 18 32 30];
X(1:8)=1/8;
Mavearge=sum(MW.*X)
The result will be:
Mavearge =
25.2500
Solution 2
MW=[16 2 32 28 44 18 32 30];
mean(MW)
ans =
25.2500
Q 5:Fully developed flow moving a 40 cm diameter pipe has the following velocity
profile:
Radius r, cm 0.0 2.5 5.0 7.5 10.0 12.5 15.0 17.5 20.0
Velocity v, m/s 0.914 0.890 0.847 0.795 0.719 0.543 0.427 0.204 0
Find the volumetric flow rate Q using the relationship Q = ∫ .
Where r is the radial axis of the pipe, R is the radius of the pipe and v is the velocity.
Solve the problem using two steps.
(a) Fit a polynomial curve to the velocity data using polyfit.
135
(b) Integrate the equation using int.
Solution:
R=[0,2.5,5,7.5,10,12.5,15,17.5,20]/100;
V=[0.914, 0.890, 0.847, 0.795, 0.719, 0.543, 0.427, 0.204,0];
P=polyfit(R,V,3);
syms r
Equ=P(1)*r^3+ P(2)*r^2+ P(3)*r+P(4);
Q=single(int(2*pi*r*Equ,0,0.20))
The result will be:
Q=
0.0582
Q 6:Use the following set of pressure-volume data to find the best possible virial
constants (B and C) for the equation of state shown below. R=82.05 ml atm/gmol K and
T= 303 K.
136
Solution:
Vol=[420,368,333,326,312,242,207];
Pre=[0.5,2,3,6,8,10,11];
Poly=polyfit(Vol,Pre,3);
symsV
Equ=Poly(1)*V^3+Poly(2)*V^2+Poly(3)*V+Poly(4);
Q=single(int(Equ,V,5,2))
The result will be:
Q=
1.9726e+002
Q 9:A liquid mixture of benzene and toluene is in equilibrium with its vapor in
closed system. At what temperature would the vapor phase composition of both benzene
and toluene 50% at equilibrium, given that the pressure in closed container is 1.4 atm?
137
T=
365.8376
Q 10:The Redlich-Kwong equation of state is given byP =
Where R= the universal gas constant [=0.518 kj/(Kg K)], T= absolute temperature
(K), p= absolute pressure (KPa). And v = volume of a Kg of gas (m3/Kg). The parameters
a and b are calculated by a =0.427 b=
Where pc= critical pressure (KPa) and Tc = critical temperature (K). As a chemical
engineer, you are asked to determine the amount of methane fuel (pc = 4600 KPa and T c =
191 K) that can be held in a 3 m3 tank at temperature of -40 oC with a pressure of 65,000
KPa.
Solution:
T=-40+273.15;
Tc=191;
P=65000;
Pc=4600;
R=0.518;
a=0.427*(R^2*Tc^2.5)/Pc;b=0.0866*(R*Tc)/Pc;
x=[0.1:0.1:2]*(R*T)/P;
y=(R*T)./(x-b)-a./(x.*(x+b)*sqrt(T));
v=interp1(y,x,P)
amount_of_methane=3/v
The result will be:
v=
0.0028
amount_of_methane =
1.0665e+003
Q 11:Reported values for the virial coefficient of isopropanol vapor at 200 oC are:
B=-388 cm3/moland C=-26000 cm6/mol2calculate V and Z for isopropoanol at 200
o
C and 10 bar using virial equation
Solution:
Re-write the equation as below:
( )
The absolute temperature is T=473.15 K, and appropriate value of gas constant is
R=83.14 cm3 bar/mol K. type the code in command window.
T=473.15;
P=10;
R=83.14;
138
B=-388;
C=-26000;
V=(R*T)/P;
for i=1:10
V=((R*T)/P)*(1+(B/V)+(C/V^2));
end
V
Z=(P*V)/(R*T)
V=
3.4877e+003
Z=
0.8866
Solution:
Xw=0:0.1:1;
Mww=18e-3;
Mwe=46e-3;
xw=(Xw*Mww)./(Xw*Mww+(1-Xw)*Mwe)
plot(Xw,xw,'k*-')
xlabel('Mass fraction of water');
ylabel('Mole fraction of water')
title('Figure ( ) mole fraction vs weight fraction')
139
Figure ( ) mole fraction vs weight fraction
1
0.8
0.4
0.2
0
0 0.2 0.4 0.6 0.8 1
Mass fraction of water
Q 13:The reaction rate constant for a first-order reaction given by the Arrhenius law
k=A e-E/RT, at temperatures from 300 K to 600 K and 10 K temperature intervals. Plot the
reaction rate constant with respect to temperature and x-axis and y-axis labels if you know
that the activation energy is E=20000 cal/mol and the pre-exponential factor is A=1013 s-1
and R=1.987.
Solution:
T=300:10:600;
k=10^13*exp(-20000./(1.987*T));
plot(T,k)
xlabel('Temperature K')
ylabel('Reaction rate constant')
5
x 10
6
5
Reaction rate constant
0
300 350 400 450 500 550 600
Temperature K
140
At Bubble point ∑yi=∑Ki×xi =1
Solution:
Write the following code
X1=0:.1:1;
X2=1-X1;
T=75;
P1=exp(14.2724-2945.47/(T+224));% Vapor pressure of acetonitrile
P2=exp(14.2043-2972.64/(T+209));% Vapor pressure of nitromethane
for m=1:11
for Pt=.1:.01:120;
K1=P1/Pt; % acetonitrile
K2=P2/Pt; % nitromethane
sum=K1*X1(m)+K2*X2(m);
if sum<1
break
end
end
Press(m)=Pt;
Y1(m)=K1*X1(m);
end
plot(X1,Press,'k-+',Y1,Press,'k-*')
axis ([0 1 20 100])
xlabel('x,y for acetonitrile')
ylabel('Pt (kpa)')
title('Pxy diagram of system acetonitrile/nitromethane system')
80
Pt (kpa)
60
40
20
0 0.2 0.4 0.6 0.8 1
x,y for acetonitrile
141