Sie sind auf Seite 1von 13

Chapter 1.

Introduction to different solution algorithms using MATLAB with examples and


related codes

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:

1 – System of linear equations “\” operator or “inv” function


2 – Single nonlinear algebraic equations “fzero” function
3 – System of nonlinear algebraic equations “fsolve” function
4 – System of ordinary differential equations “ode45” and similar solvers
5 – Non-linear least squares and optimization “lsqnonlin”
6 – Numerical integration for definite integrals “integral”

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.

1. System of linear equations


A generic form of a linear-equation system can be written in a compact notation as:
Ax = b (1)
Where A is the matrix of coefficients; x is the vector of the unknown; and b is a vector of numerical
values at the right-hand side of the expression. Usually A is a square matrix nxn (n equations and n
unknowns) with non-null determinants, and x and b are column vectors nx1. The condition of a
non-null determinant ensures that the system has a solution.
The first way to solve the system in Matlab is the use of the pseudo-inverse operator, “\”. The
following short code represents an example of this first possibility: a system of four equations and
four unknowns is solved, and verification is also made. This last check can be implemented, after
the solution has been found, by back-substitution of x vector in the equation (1):
Ax - b = 0 (2)
If the found solution is correct, a vector of zeros—or, at least, values below machine precision
(numbers of 1e-14 as order of magnitude)—will be found.

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)

Output of Example 1.1


solution
-1.5333
0.4000
2.4667
0.2667
---------------------
check
---------------------
1.0e-15 *
0.8882
0
0
0
The second common possibility to solve a linear equations system in Matlab involves the use of the
intrinsic Matlab function “inv,” which returns the inverse of a matrix. This method is illustrated in
the following examples.

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)

Output of Example 1.2


solution
-1.5333
0.4000
2.4667
0.2667
---------------------
check
---------------------
1.0e-14 *
-0.0888
-0.0444
0
-0.1332
2. Single non-linear algebraic equation
This kind of numerical problem occurs frequently in chemical-engineering calculations and, in
Matlab, a specific intrinsic function is provided to perform this task: the “fzero” function. The
problem of solving a nonlinear equation must be previously written in the general form:
f ( x) = 0 (3)
The “fzero” function implements automatically several algorithms (Newton, interpolation, regula
falsi, etc.) to find a value of x that renders the function f(x) < eps where eps is a numerical
approximation of the mathematical zero. The value of eps can be chosen by the user; otherwise
“fzero” will try to find the best approximation.
As an example of the use of “fzero,” suppose we want to find a value of x that is a solution of the
following nonlinear equation:
3
f ( x) = 3sin( x) - 0.02 x 2 + =0 (4)
3+ x
The first possibility, with a minimal use of “fzero”, is represented by the following syntax:
x=fzero(‘fname’,x0)
(5)
Where:
x solution obtained at the maximum precision allowable
fname name of Matlab file in which the function to be solved is defined
x0 guess of the solution, initial starting point for the iterations

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

Output of Example 2.1


solution x = -0.39248
function in x = 2.2204e-16

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

%% example of fzero with interval


%-----------------------------------
clc, clear
xmin=-1;
xmax=+1;
xr=fzero('fun',[xmin xmax]);
fr=fun(xr);
disp(['solution x = ',num2str(xr)])
disp([function at x = ',num2str(fr)])
x=xmin:0.01:xmax;
y=fun(x);
plot(x,y,xr,fr,'ro')
grid

Output of Example 2.2


solution x = -0.39248
function in x = 2.2204e-16

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)

Output of Example 3.1

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.

4. System of ordinary differential equations


In the Matlab environment, several solvers are provided that are devoted to the solution of a vast
category of differential equations. Because we are particularly interested in solving a specific class
of differential equations that are ordinary differential equations with initial conditions, we focus our
attention to the solved, which is named “ode45.”
From a mathematical point of view, a generic system of n ordinary differential equations in explicit
form can be written as:
dy1
= f1 (t , y1 , y2 ,....., yn )
dt
dy2
= f 2 (t , y1 , y2 ,....., yn )
dt
(11)
...
...
dyn
= f n (t , y1 , y2 ,....., yn )
dt

Or in a more compact form as:

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 [ dy ] = der( t,y )


% ODE
%-----------------------------
dy=2*y-t;
end

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
… …
… …

In graphical form it appears as follows:

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')

function [ dc ] = system_ode( t,c )


%% ODE system
%------------------------------------
global k1 k2
ca=c(1);
cb=c(2);
cc=c(3);
r1=k1*ca;
r2=k2*cb;
dc(1)=-r1;
dc(2)=+r1-r2;
dc(3)=+r2;
dc=dc';
end

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';

Output of Example 4.2


The numerical output is of the form:
t c(1) c(2) c(3)
0 10.0000 0 0
1.0000 9.0303 0.9498 0.0199
2.0000 8.1546 1.7693 0.0761
3.0000 7.3639 2.4727 0.1634
4.0000 6.6498 3.0728 0.2774
5.0000 6.0049 3.5810 0.4141
6.0000 5.4226 4.0074 0.5700
7.0000 4.8968 4.3614 0.7418
8.0000 4.4219 4.6514 0.9267
… … … …
… … … …
By plotting the three components of the solution (c(1), c(2) and c(3)) as a function of time, the
following plot is obtained:

5. Nonlinear least squares and optimization

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

Or alternatively, in a relative form:


2
Ndat �y sper - y calc �
= �� sper
j j
FOBJ � (18)
j =1 � yi �
In both cases, the adjustable parameter, appearing implicitly in calculated y values, requires
evaluation of the residuals defined as:
rj = y sper
j - y calc
j (19)
In Matlab (and particularly in its toolboxes, such as “optimization toolbox”), many algorithms are
available for minimization of a multi-parameter objective function, optimization, nonlinear
programming, etc. For our calculation, we have chosen a general purposes Matlab function,
“lsqnonlin,” which is devoted to the problem of nonlinear least-squares fitting. The minimal syntax
of this command is the following:

[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)')

Output of Example 5.1


A = 8.4614
B = 2159.7815
C = 291.435
f = 369400.1259

6. Numerical integration for definite integrals


In this paragraph, the numerical integration of a function (definite integral) will be described.
Suppose we have a function f(x) of arbitrary complexity: Even if the exact definite integral could
not exist, Matlab contains a special function, “integral”, that returns an approximation of the
integral:
b
I =�
f ( x )dx (21)
a

The function has the following syntax:


Q=integral(@fun_int,a,b)
Where:
Q numerical value of the integral of f(x) over the interval [a,b]
fun_int name of function to be integrated (note that the function name is passed as
@fname instead of “fname”)
a lower bound of the integration interval
b upper bound of the integration interval

Example 6.1
Suppose we wish to calculate the numerical value of the following integral:
1

[ cos( x)] dx
2
q=� (22)
0

This integral has the general exact solution:


1
q = [ x + sin( x ) cos( x) ] + c (23)
2
And for an interval [a b]:
1 1
q = [ b + sin(b) cos(b) ] - [ a + sin( a) cos( a) ] (24)
2 2
In the following Matlab code, the numerical value of the integral (22) is calculated, and this result is
compared with the exact analytical value furnished by Eq. (24).

%% 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

Output of Example 6.1

------- Exact Integral --------------------


Int = 0.72732

------- Numerical value --------------------


Int = 0.72732 relative error = 2.2204e-16

Das könnte Ihnen auch gefallen