Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views12 pages

Tutorial 3

This document provides a tutorial on solving nonlinear equations using MATLAB, detailing the definitions, examples, and available solvers such as fzero and fsolve. It includes specific examples demonstrating how to find roots and solve systems of equations, along with guidance on setting initial guesses and handling tolerances. Additionally, it discusses limitations and offers insights into troubleshooting common issues encountered during numerical solutions.

Uploaded by

mohdubaidamu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views12 pages

Tutorial 3

This document provides a tutorial on solving nonlinear equations using MATLAB, detailing the definitions, examples, and available solvers such as fzero and fsolve. It includes specific examples demonstrating how to find roots and solve systems of equations, along with guidance on setting initial guesses and handling tolerances. Additionally, it discusses limitations and offers insights into troubleshooting common issues encountered during numerical solutions.

Uploaded by

mohdubaidamu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Tutorial 3: Solving Non-Linear Equations

in MATLAB
Nonlinear Equations
An equation in which the maximum degree of a term is 2 or more than two is called a nonlinear
equation.
For example
3x2 + 2x + 1 = 0 ……. (1)
3x + 4y = 5 ……. (2)
These are the examples of nonlinear equations, because equation 1 has the highest degree of 2 and the
second equation has variables x and y.
Nonlinear equation values when plotted on a graph forms a curve

In MATLAB, the following solvers are available:


1. fzero
2. fsolve
3. roots

fzero
The fzero command is a function file. The algorithm, created by T. Dekker, uses a combination of
bisection, secant, and inverse quadratic interpolation methods. The Optimize Live Editor task provides a
visual interface for fzero.
x = fzero(fun,x0) tries to find a point x where fun(x) = 0. This solution is where fun(x) changes sign; fzero
cannot find a root of a function such as x^2.
x = fzero(fun,x0,options) uses options to modify the solution process. The following options may be
used.

Level of display:
• 'off' displays no output.
Display • 'iter' displays output at each iteration.
• 'final' displays just the final output.
• 'notify' (default) displays output only if the function does not converge.
Check whether objective function values are valid.
• 'on' displays an error when the objective function returns a value that is complex,
FunValCheck
Inf, or NaN.
• The default, 'off', displays no error.
Specify one or more user-defined functions that an optimization function calls at each
OutputFcn iteration, either as a function handle or as a cell array of function handles. The default is
none ([]).
Plot various measures of progress while the algorithm executes. Select from predefined
plots or write your own. Pass a function handle or a cell array of function handles. The
PlotFcns default is none ([]).
• @optimplotx plots the current point.
• @optimplotfval plots the function value.
TolX Termination tolerance on x, a positive scalar. The default is eps, 2.2204e–16.

Example 3.1
Find a root for f(x) = zero, where the function f(x) = x3 – 2x – 5. Take initial guess of x=2
Solution
First, write a file called f.m
function y = f(x)
y = x.^3 - 2*x - 5;

Save f.m on your MATLAB path.


Find the zero of f(x) near 2 by the following code
fun = @f; % function
x0 = 2; % initial point
z = fzero(fun,x0)

Command prompt would show:


z =
2.0946

fsolve
Solves a problem specified by

F(x) = 0

for x, where F(x) is a function that returns a vector value.

x is a vector or a matrix.

The fsolve command solves a system of nonlinear equations. It utilized the Levenberg-Marquardt and
trust-region methods that are based on the nonlinear least-squares algorithms. By default fsolve
chooses the trust-region dogleg algorithm. The algorithm is a variant of the Powell dogleg method. The
trust-region algorithm is a subspace trust-region method and is based on the interior-reflective Newton
method. Each iteration involves the approximate solution of a large linear system using the method of
preconditioned conjugate gradients (PCG). The Levenberg-Marquardt algorithm uses a search direction
that is a cross between the Gauss-Newton direction and the steepest descent direction.

Limitations
• The function to be solved must be continuous.
• When successful, fsolve only gives one root.
• The default trust-region dogleg method can only be used when the system of equations is
square, i.e., the number of equations equals the number of unknowns. For the Levenberg-
Marquardt method, the system of equations need not be square.

x = fsolve(fun,x0) starts at x0 and tries to solve the equations fun(x) = 0, an array of zeros.
x = fsolve(fun,x0,options) solves the equations with the optimization options specified in
options. Use optimoptions to set these options.

[x,fval,exitflag,output] = fsolve(___) for any syntax, returns the value of the objective
function fun at the solution x, returns a value exitflag that describes the exit condition of fsolve,
and a structure output with information about the optimization process.

exitflag — gives an integer between -3 and 4, indicating the reason why fsolve stopped.

Example 3.2
Finding Equilibrium Concentrations for the reaction H2O + CO <=> CO2 + H2. Given the Equilibrium
constant, K = 1.44
For an equimolar feed of H2O and CO, compute the equilibrium conversion.

Solution

C_H2O = (C_H20)0 * (1-Xe)


C_CO = (C_H20)0 * (1-Xe)
C_H2 = (C_H20)0 * Xe
C_CO2 = (C_H20)0 * Xe
K = C_CO2*C_H2/(C_H20*C_CO)

Steps to follow:
• Write a script m-file in Matlab for the Equilibrium Conversion
• Start with a skeleton script
• Use Code cells to break-up the code
• Plot the function to visualize the guess
• Review a common syntax problem for element-wise operations
• Iterate through the cells
• Review the initial guess and solutions
% K = C_CO2*C_H2/(C_H20*C_CO)
% solve Xe^2/(1-Xe)^2 = 1.44

%% Clear and Close


clear all;
close all;
%% Define the Anonymous Function
f = @(Xe) 1.44 - Xe.^2./(1-Xe).^2;

%% Plot Solution
x = .4:0.001:.6;
y = f(x);
plot(x,y,'color','red');

%% Specify Initial Guess and


x_guess = 0.5;
fsolve(f,x_guess)

Executing this in live editor, gives

Equation solved.

fsolve completed because the vector of function values is near zero


as measured by the value of the function tolerance, and
the problem appears regular as measured by the gradient.

<stopping criteria details>


ans = 0.5455

Example 3.3: Multi-Dimensional Systems Example


Solve the set of equations:
0 = K1-(yCO*yH2^3)/(yCH4*yH2O)*p^2;
0 = K2 - ((yCO^2)*(yH2^2))/(yCO2*yCH4);
0 = (2*yCH4 + yH2 + yH2O)*n - nH2f;
0 = (0.5*yCO + yCO2 + 0.5*yH2O)*n - nO2f;
0 = (yCH4 + yCO + yCO2)*n - nCf;
0 = yCO + yCO2 + yCH4 + yH2 + yH2O - 1;
Given
K1 = 25.82; K2 = 19.41; p = 1;
nCf = 1; nH2f=0.5; nO2f = 0.5;

Solution
No way to graph this case
Must have knowledge of the problem to specify and initial guess

function gasexample

[X, fval, exitflag] = fsolve(@gasifier_eq, [0.2 0.2 0.2 0.2 0.2 1.5])

if exitflag ~= 1 then
disp('Something is wrong!')
end

function zero = gasifier_eq(X)

yCO = X(1);
yCO2 = X(2);
yH2 = X(3);
yCH4 = X(4);
yH2O = X(5);
n = X(6);

K1 = 25.82;
K2 = 19.41;
p = 1;
nCf = 1; nH2f=0.5; nO2f = 0.5;

eq1 = K1-(yCO*yH2^3)/(yCH4*yH2O)*p^2;
eq2 = K2 - ((yCO^2)*(yH2^2))/(yCO2*yCH4);
eq3 = (2*yCH4 + yH2 + yH2O)*n - nH2f;
eq4 = (0.5*yCO + yCO2 + 0.5*yH2O)*n - nO2f;
eq5 = (yCH4 + yCO + yCO2)*n - nCf;
eq6 = yCO + yCO2 + yCH4 + yH2 + yH2O - 1;

zero = [eq1; eq2; eq3; eq4; eq5; eq6];

Equation solved.

fsolve completed because the vector of function values is near zero


as measured by the value of the function tolerance, and
the problem appears regular as measured by the gradient.

X =

0.6475 0.0339 0.2638 0.0443 0.0104 1.3779

fval =

1.0e-11 *

0.3737
0.0085
0
0
0
-0.0000

exitflag =

Published with MATLAB® R2022b

Example 3.4: Tolerance Concern Example


𝑣(𝐶𝐴0 −𝐶𝐴 )
Solve this Equation V− =0
𝑘𝐶 2 𝐴

Given
CA0= 2000 mol/m3
V = .010 m3
v = .0005 m3/s
k = .00023 m3/mol/s
Plotting will guide that solution is near 500
With initial guess of 500, fsolve gives the answer as 500 under default conditions. It could be observed
that there is significant error with this answer. Therefore, reduce the default tolerance to increase the
accuracy.

Solution

Know your tolerance

with the information given below, solve for the exit concentration. This should be simple.

clear all; close all; clc

Cao = 2000; % mol/m^3


V = .010; % m^3
nu = .000500; % m^3/s
k = .000230; % m^3/mol/s

function we need to solve

f = @(Ca) V - nu*(Cao - Ca)./(k*Ca.^2);

plot the function to estimate the solution


c = linspace(200,600);
plot(c,f(c))
ylim([-1 1]) % limit the y-range to see the zero easier
xlabel('C_A')
ylabel('f(C_A)')
ylim([-0.02 0.02])
% we want the value of C_A that makes f(C_A)=0. this happens around C_A=0.5

cguess = 500;
c = fsolve(f,cguess)
% it is a little weird that the solution is the same as our initial guess.
% Usually the answer is at least a little different!

Equation solved at initial point.

fsolve completed because the vector of function values at the initial point
is near zero as measured by the value of the function tolerance, and
the problem appears regular as measured by the gradient.

c =

500

check your solution


z = f(c);
zL = z.* 1000 % this puts the zero in Liters
% this is not really that close to zero, especially when you look at the
% units in L!

zL =
-3.0435

closer look at fsolve


Let's output some more information.

options = optimset('Display','iter');
[X,FVAL,EXITFLAG,OUTPUT] = fsolve(f,cguess,options)
% It should be a warning that zero iterations were taken! Our guess was
% probably not that good! The EXITFLAG=1 means the function ended ok as far
% as fsolve is concerned.

Norm of First-order Trust-region


Iteration Func-count f(x) step optimality radius
0 2 9.26276e-06 1.85e-07 1

Equation solved at initial point.

fsolve completed because the vector of function values at the initial point
is near zero as measured by the value of the function tolerance, and
the problem appears regular as measured by the gradient.

X =

500

FVAL =

-0.0030

EXITFLAG =

OUTPUT =

struct with fields:

iterations: 0
funcCount: 2
algorithm: 'trust-region-dogleg'
firstorderopt: 1.8526e-07
message: 'Equation solved at initial point.↵↵fsolve completed because the
vector of function values at the initial point↵is near zero as measured by the value
of the function tolerance, and↵the problem appears regular as measured by the
gradient.↵↵<stopping criteria details>↵↵Equation solved. The final point is the
initial point.↵The sum of squared function values, r = 9.262760e-06, is less than
sqrt(options.FunctionTolerance) = 1.000000e-03.↵The relative norm of the gradient of
r, 1.852552e-07, is less than options.OptimalityTolerance = 1.000000e-06.'

The problem is bad scaling because the underlying units are stored in m^3, which results in very small numbers that
are close to zero. So, fsolve sees a number it thinks is close to zero, and stops. One way to fix this is to decrease the
tolerance on what constitutes zero.

options = optimset('TolFun',1e-9);
cguess = 500;
[c2,FVAL,EXITFLAG,OUTPUT] = fsolve(f,cguess,options)
z2 = f(c2);
z2% much closer to zero.

sprintf('The exit concentration is %1.2f mol/L', c2)

Equation solved.

fsolve completed because the vector of function values is near zero


as measured by the value of the function tolerance, and
the problem appears regular as measured by the gradient.

c2 =

559.5545

FVAL =

-1.2487e-06

EXITFLAG =

OUTPUT =

struct with fields:

iterations: 6
funcCount: 14
algorithm: 'trust-region-dogleg'
firstorderopt: 5.3309e-11
message: 'Equation solved.↵↵fsolve completed because the vector of function
values is near zero↵as measured by the value of the function tolerance, and↵the
problem appears regular as measured by the gradient.↵↵<stopping criteria
details>↵↵Equation solved. The sum of squared function values, r = 1.559359e-12, is
less than↵sqrt(options.FunctionTolerance) = 3.162278e-05. The relative norm of the
gradient of r,↵5.330927e-11, is less than options.OptimalityTolerance = 1.000000e-09.'

z2 =

-1.2487e-06

ans =

'The exit concentration is 559.55 mol/L'

or we can scale the equation to use more appropriate units

Cao = 2; % mol/L
V = 10; % L
nu = .500; % L/s
k = .230; % L/mol/s

function we need to solve

f = @(Ca) V - nu*(Cao - Ca)./(k*Ca.^2);


cguess = .5;
c3 = fsolve(f,cguess)
% it is a little weird that the solution is the same as our initial guess.
% Usually the answer is at least a little different!

Equation solved.

fsolve completed because the vector of function values is near zero


as measured by the value of the function tolerance, and
the problem appears regular as measured by the gradient.

c3 =

0.5596

check your solution


z = f(c3)

% much closer

z =

-3.9098e-12

'done'

ans =

'done'

Published with MATLAB® R2022b

roots
syntax is r = roots(p)

returns the roots of the polynomial represented by p as a column vector. Input p is a vector containing
n+1 polynomial coefficients, starting with the coefficient of xn. A coefficient of 0 indicates an
intermediate power that is not present in the equation. For example, p = [3 2 -2] represents the
polynomial 3x2+2x−2.

The roots function solves polynomial equations of the form p1xn+...+pnx+pn+1 = 0. Polynomial equations
contain a single variable with nonnegative exponents.

Example 3.5

Find the roots of the Van Der Waal equation:

V3 – ((pnb+nRT)/p)V2 + (n2a/p)V – n3ab/p = 0

Coefficients may be written as [1 -(pnb+nRT/p) (n2a/p) – n3ab/p]

Given a = 3.49e4; b = 1.45; p = 679.7; T = 683; n = 1.136; R = 10.73;


Solution

solving one-dimensional nonlinear equations


clear all; clc; close all;
% in general we solve nonlinear equations by putting them in the form:
% f(x) = 0%

application in thermodynamics
we need to find the volume that solves the van der waal equation:

where a and b are constants. Our goal is to find where this function is equal to zero. We can do that graphically and
numerically.

% numerical values of the constants


a = 3.49e4;
b = 1.45;
p = 679.7;
T = 683;
n = 1.136;
R = 10.73;

% we define a function handle for the van der waal equation


vanderwaal = @(V) V^3 - (p*n*b+n*R*T)/p*V^2 + n^2*a/p*V - n^3*a*b/p;

% we saw in the plotting tutorial that the solution is near V = 5.


[V, fval, EXITFLAG] = fsolve(vanderwaal,5)

Equation solved.

fsolve completed because the vector of function values is near zero


as measured by the value of the function tolerance, and
the problem appears regular as measured by the gradient.

V =

5.0943

fval =

1.9949e-10

EXITFLAG =

an alternative approach using roots


The van der waal equation is just a cubic polynomial in V. Matlab has a roots function that gives you all the zeros of a
polynomial. let our equation be: 0 = A*V^3 + B*V^2 + C*V + D by inspection of the Van der Waal eqn, you can identify
the values of A, B, C and D

A = 1;
B = -(p*n*b+n*R*T)/p;
C = n^2*a/p;
D = -n^3*a*b/p;
roots([A B C D])

% there are three solutions, because it is a cubic polynomial. Two of the


% solutions are imaginary, which have no physical meaning for volume. The
% other solution is the same as the numerically found value. Note, however,
% that we did not have to use an initial guess! roots can be found
% analytically, so no initial guess is required.

ans =

5.0943 + 0.0000i
4.4007 + 1.4350i
4.4007 - 1.4350i

Published with MATLAB® R2022b

You might also like