Beruflich Dokumente
Kultur Dokumente
Several numerical methods are included in Matlab as system functions, which can be called within
user functions. In the present introductory chapter, the Matlab functions used through the exercises
of the book are briefly described both for what concerns the syntax and the used numerical
algorithms. These functions can be grouped in the following categories according to the specific
numerical problem:
These topics are described with the minimum requirement of syntax, but these numerical functions
can be used in a more advanced form by passing extra parameters and by choosing suitable options
for a fine-tuning of the command. In this way, more complex problems can be solved.
Example 1.1
%% method of inverse operator
%----------------------------
clc,clear
a=[ 3 1 2 1 ;
1 2 1 1 ;
0 0 1 2 ;
3 3 3 0 ];
b=[ 1; 2; 3; 4];
x=a\b;
disp(' solution ')
disp(x)
disp('---------------------')
disp(' check ')
disp('---------------------')
v=a*x-b;
disp(v)
Example 1.2
%% method of inverse matrix
%-----------------------------------
clc,clear
a=[ 3 1 2 1 ;
1 2 1 1 ;
0 0 1 2 ;
3 3 3 0 ];
b=[ 1; 2; 3; 4];
x=inv(a)*b;
disp(' solution ')
disp(x)
disp('---------------------')
disp(' check ')
disp('---------------------')
v=a*x-b;
disp(v)
Example 2.1
As a first example of the use of this command, the following code illustrates the minimal
requirement for the solution of equation (4).
%% example of fzero
%---------------------
clc, clear
x0=0.3;
xr=fzero('fun',x0);
fr=fun(xr);
disp([solution x = ',num2str(xr)])
disp(['function at x = ',num2str(fr)])
% plot
x=-1:0.01:1;
y=fun(x);
plot(x,y,xr,fr,'ro')
grid
xlabel('x')
ylabel('f(x)')
function [ fx ] = fun( x )
% function
%---------------------------------
fx=3*sin(x)-0.02.*x.^2+3./(3+x);
end
In the figure, a plot of the function is reported with an indication (red circle) of the solution found.
If the user is not able to give a guess for the solution, x0, a second possibility to solve the equation
is to pass a search interval to the “fzero” command according to the following syntax:
x=fzero(‘fname’,[x1 x2]) (6)
Where:
x solution obtained at the maximum precision allowable
fname name of Matlab file in which the function to be solved is defined
[x1 x2] is a vector with two elements defining a search interval into which the
solution will be searched for (if exists)
Note that in this second approach, the user must be sure that the function changes sign at the two
extremes of the interval (x1 and x2). The following example, Example 2.2, illustrates this method
applied to the same function of Example 2.1.
Example 2.2
Obviously, the solution for x—found using each of the two methods—is exactly the same.
3. System of non-linear algebraic equations
Another common problem in chemical-engineering calculation is represented by a group of non-
linear algebraic equations that must be solved simultaneously. The formulation of such a problem is
the multi-dimensional case of the problem of the previous section 2 and can be written in compact
vector notation as:
ur r
f ( x) = 0 (7)
More explicitly:
f1 ( x1 , x2 ,......, xn ) = 0
f 2 ( x1 , x2 ,......, xn ) = 0
f 3 ( x1 , x2 ,......, xn ) = 0
(8)
...
...
f n ( x1 , x2 ,......, xn ) = 0
In this case, the n functions must be solved simultaneously by finding the set of x values that render
equal to zero all of the mentioned functions. The Matlab function dedicated to this task is called
“fsolve,” and, like “fzero”, it implements different numerical algorithms (Newton, conjugate
gradient, etc.) that are applied for searching the desired solution. The syntax of “fsolve” is similar to
that seen for “fzero” but is referred to the multidimensional problem:
x=fsolve(‘sysname’,x0)
(9)
Where:
x solution vector obtained at the maximum precision allowable (x1, x2, …)
sysname name of Matlab file in which the system of equations to be solved is defined
x0 vector of initial estimate for the solution used as starting point for the
iterations
Example 3.1
As an example of the use of “fsolve” function, suppose we must find the solution to the following
non-linear system of three simultaneous equations.
x12 + x2 - 37 = 0
x1 - x22 - 5 = 0 (10)
x1 + x2 + x3 - 3 = 0
In the following code, the solution is obtained through the use of the “fsolve” command:
%% fsolve example
%--------------------------------
clc, clear
x0=[1 1 1];
x=fsolve('funsys',x0);
res=funsys(x);
disp(['solution x1 = ',num2str(x(1))])
disp(['solution x2 = ',num2str(x(2))])
disp(['solution x3 = ',num2str(x(3))])
disp(' ')
disp('residuals')
disp(res)
solution x1 = 6
solution x2 = 1
solution x3 = -4
residuals
1.0e-07 *
0.0020 -0.3405 -0.0000
As we can see from the output, the functions have been solved with an approximation, that is, 1e-7,
as an order of magnitude.
u
r
d y ur u r
= f (t , y ) (12)
dt
In this notation, t is the independent variable (often defined as the “integration variable”); and y are
the unknown functions to be evaluated as function of t over a specified interval (the integration
interval). To solve the system defined in Equations (11) or (12), we must know the initial values of
the unknown:
yi t =0 = yi0 i = 1....n (13)
Among the several solvers for this problem that are present in Matlab, the solver “ode45”
implements the integration algorithm of Runge and Kutta with formulas of the 4th and 5th order. The
syntax of the command is the following:
[t,y]=ode45(‘odesys’,tspan,y0]
Where:
t in output is a vector of t values in correspondence of which the
solution is furnished
y is the solution of the ODEs represented by a matrix, the columns of
which are the tabulated values of yi at the desired times
‘odesys’ is the name of the Matlab file in which the ODE system is defined
tspan is a column vector of t values at which the solution is desired
y0 is a column vector containing the initial values of yi
Example 4.1
Suppose we must numerically solve the following single differential equation:
dy
= 2y -t (14)
dt
With initial condition: y t =0 = 1
For this particular ODE, the exact analytical solution is known and can be used in comparison with
the approximate numerical solution obtained from Matlab solver “ode45.” The exact solution of
ODE (14) is:
1
(
y = 3e 2t + 2t + 1
4
) (15)
The following Matlab short code represents the solution of the problem.
%% example of ode45
%---------------------------------
clc,clear
t0=0;
tend=1;
ta=t0:0.001:tend;
ya=fun(ta);
dt=0.025;
tspan=t0:dt:tend;
y0=1;
[t,y]=ode45('der',tspan,y0);
plot(ta,ya,t,y,'ro')
grid
xlabel('t')
ylabel('y')
legend('analytical solution','ODE45 solution')
function [ y ] = fun( t )
%% exact analytical solution
%-------------------------------
y=0.25*(3*exp(2*t)+2*t+1);
end
Output of Example 4.1
The function “ode45” produces as output a table of numbers that represent the solution of the
problem at the time instants required. The table has the following form:
t y
0 1.0000
0.0250 1.0510
0.0500 1.1039
0.0750 1.1589
0.1000 1.2161
0.1250 1.2755
0.1500 1.3374
0.1750 1.4018
… …
… …
From the plot, it is evident that the accuracy obtained with “ode45” is very high, and this command
can be adopted for the majority of the problems.
Example 4.2
Consider a batch reactor in which two consecutive reactions occur. For this system, the material
balance results in a set of three coupled differential equations, for which the initial condition is
represented by the initial concentration in the reactor. The system to be solved is then:
dC A
= -k1C A
dt
dCB
= + k1C A - k2CB (16)
dt
dCC
= + k 2CB
dt
Initial condition is: CA°=10 mol/L, CB°=0 mol/L, CC°=0 mol/L
Kinetic constants: k1=0.102 1/min, k2=0.041 1/min
The following code solves the ODE system and produces a plot with the evolution in time of the
three components of the solution.
%% ODE examples – consecutive reactions
%-------------------------------------------
clc,clear
global k1 k2
k1=0.102;
k2=0.041;
t0=0;
tend=100;
dt=1;
tspan=t0:dt:tend;
c0=[10 0 0];
[t,c]=ode45('system_ode',tspan,c0);
plot(t,c(:,1),t,c(:,2),t,c(:,3))
grid
xlabel('Time (min)')
ylabel('Concentration (mol/L)')
legend('Ca','Cb','Cc')
Note that in the case of a multi-dimensional problem (system of ODE), the solver “ode45” requires
that the function in which ODEs are defined returns a column vector of the derivatives. This
requires that after the definition of the derivatives one by one, a transposition operation is
necessary: dc=dc';
Another common task in chemical-engineering calculations and scale-up activity is the fitting of
experimental data collected in laboratory scale with a mathematical model that allows one to
properly design unit operation. This operation can be conducted in a straightforward way when the
model is linear with respect to the adjustable parameters, but it could be difficult if the model to be
fitted has a nonlinear characteristic. The described task can be addressed by considering that the
best adjustable parameters are those that correspond to the minimum of an objective function,
which is constructed as the residual sum of squares (least-squares approach). Such an objective
function is in the following form:
Ndat
FOBJ = �( y sper )
2
j - y calc
j (17)
j =1
[kp,fv]=lsqnonlin(‘fobjname’,k0,lb,ub)
Where:
kp vector containing the values of the parameters in correspondence to minimum
(best parameters)
fv minimum value found for the objective function
fobjname name of Matlab file in which the residuals (Eq. 19) between experimental and
calculated values are evaluated. The objective function, such as Eq. (17) or
(18), is automatically built.
k0 vector of initial values, initial estimates, of the adjustable parameters
lb vector of lower bounds for each parameter
ub vector of upper bounds for each parameter
Example 5.1
Suppose we have collected several experimental data for vapour pressure of water as a function of
temperature and that we must store these data in an Excel file in table form, such as the following:
We want to fit a precise expression to these experimental data, such as the Antoine equation:
B
log10 P = A - (20)
T +C
With P expressed in mmHg, and T expressed in °C. We want to determine the three adjustable
parameters—A, B, and C—that allow the best possible description (in the sense of least-squares
principle) of the experimental data. The following Matlab code performs this task.
%%----------------------------------------
% minimization
%-----------------------------------------
clc, clear
global t p pc
%% Read data from excel
DATA=xlsread('EXPERIMENTAL DATA','A2:B31');
t=DATA(:,1);
p=DATA(:,2);
%% minimization with lsqnonlin
p0=[8 2000 200];
li=[3 1000 100];
ls=[20 3000 500];
[px, fv]=lsqnonlin('fun_obj',p0,li,ls);
sc=fun_obj(px);
disp([' A = ',num2str(px(1))])
disp([' B = ',num2str(px(2))])
disp([' C = ',num2str(px(3))])
disp([' f = ',num2str(fv)])
%% grafico
plot(t,p,'ro',t,pc,'-b')
grid
xlabel('Temperature (°C)')
ylabel('Pressure (mmHg)')
Example 6.1
Suppose we wish to calculate the numerical value of the following integral:
1
[ cos( x)] dx
2
q=� (22)
0
%% example of integral
%------------------------
clc, clear
a=0;
b=1;
ia=0.5*(a+sin(a)*cos(a));
ib=0.5*(b+sin(b)*cos(b));
iex=ib-ia;
q=integral(@fun_int,a,b);
e=abs(1-iex/q);
disp('------- Exact Integral ---------------')
disp([' Int = ',num2str(iex)])
disp(' ')
disp('------- Numerical value ---------------')
disp([' Int = ',num2str(q),' relative error = ',num2str(e)])
function [ f ] = fun_int( x )
% test function for integral
%----------------------------------
f=cos(x).^2;
end