0% found this document useful (0 votes)
34 views151 pages

LAB 1 - Lab 8 Numerical Analysis Lab

notes

Uploaded by

Arrianna Peter
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)
34 views151 pages

LAB 1 - Lab 8 Numerical Analysis Lab

notes

Uploaded by

Arrianna Peter
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/ 151

Chemical Engineering

Laboratory III
LAB #1
LAB #1
• Introduction to MATLAB as a technical computing tool.
• Defining and managing variables.
MATLAB
A computer program that provides the user
to perform many types of calculations. In
particular, tool to implement numerical
methods.
The Environment

Workspace:
shows a list of
variables created
by MATLAB.

Command window: Type your


instructions here and press
ENTER to execute them.
The way to operate MATLAB
• is by entering the commands (Calculations and
Creating plots) one at a time in the command
window.
• Alternatively, such commands can be used to
create MATLAB programs (by using edit windows).
MATLAB uses three primary windows

Command window Graphics window Edit window


Used to enter commands and data. Used to display plots and graphs. Used to create and edit M-files.
MATLAB uses three primary windows (Example)

Command window Graphics window Edit window


Used to enter commands and data. Used to display plots and graphs. Used to create and edit M-files.
After starting MATLAB
the command window will be opened and the
command prompt is displayed.
>>
For each command, you get a result. Thus, you
can think of it as operating like a very fancy
calculator. i.e.:
>> 55 - 16
• Note: MATLAB has automatically assigned the
answer to a variable, ans. (refer to workspace)
Scalars
The Assignment
How we assign values to variable names. Arrays,
Vectors
This results in the storage of the values in and
Matrices
the memory location corresponding to the
variable name.
Colon
Operator
Try it yourself !!!

• >> a = 4

Scalars • >> A = 6; Function


• >> b = 3, pi; x = 1;

• >> x = 2+i*4
Character
Strings
Arrays, Vectors and Matrices
is a collection of values that are represented
by a single variable name.

1D arrays are called vectors. 2D are called matrices.

Note: The scalars used are actually matrices with one row and one column.
Challenge

Create a matrix (2x3)

𝟑 𝟏. 𝟓 𝟐
𝒙=
𝟎. 𝟏 𝟕 𝟏
Colon Operator, : Aside from creating
series of numbers, it
is a powerful tool for creating and
manipulating arrays. can be used to select
Starting value Final value
the individual rows
x = [xi ∶ dx ∶ xf ]
or/and columns of a
increment
matrix.
Functions
MATLAB defined fcn

1.linspace
2.logspace
3.rand
4.magic
5.ones
6.zeros
7.eye
8.and many more …
Character Strings
Aside from numbers, alphanumeric information can be represented by
enclosing the strings within single quotation marks

Each character in a string is one element in an array. Thus we can


combine them as in:
Challenge

The density of freshwater can be computed as a function of


temperature with the following cubic equation:
3

𝜌 = 5.5289 × 10−5 𝑇𝑐 − 8.5016 × 10−6 𝑇𝑐2


+ 6.5622 × 10−5 𝑇𝑐 + 0.99987

where ρ = density (g/cm3) and T = temperature (°C).


C

Q1: Use MATLAB to generate a vector of density ranging from


32 °F to 93.2 °F using increments of 3.6 °F.

Q2: Determine the density at T = 60.8 °F


LAB #1
• Creating and manipulating vector and matrix
Mathematical Operations

Mathematical Mathematical Array

+ Addition + Addition
- Subtraction - Subtraction
* Multiplication .* Multiplication
/ Division ./ Division
^ Power .^ Power
Try it Yourself !!!

>> 2*pi Operations with scalar quantities are handled in a


straightforward manner.
>> 2 + 9

>> a=1,b=3, c=2*a/b

>> y1 = -6^2 Exponentiation has higher priority then negation,


thus 6^2 = 36 and final answer is -36
>> y2 = (-6)^2 Parentheses can override the exponentiation term,
thus (-6)^2 = 36
The real power of MATLAB is illustrated in its
ability to carry out vector-matrix calculations
To further illustrate vector-matrix multiplication, first redefine a and b:

>> a = [1 2 3]; b = [4 5 6];

>> x1 = 2*a Mixed operations with scalars variable

>> x2 = 2/b

>> c = 2.3; x3 = c*b

>> a*b Matrix, a Matrix, b

1 2 3 × 3 4 5
𝑎(1 × 3) 𝑏(1 × 3)

3 𝑐𝑜𝑙𝑢𝑚𝑛𝑠 ≠ 1 𝑅𝑜𝑤𝑠

Note: Matrices cannot be multiplied if the


inner dimensions are unequal
Matrix, B
Try it yourself !!! 4
Matrix, a

>> A = [1 2 3]; B = [4; 5; 6]; 1 2 3 × 5


6
>> X1 = A*B 𝑎(1 × 3) 𝐵(3 × 1)
3 𝑐𝑜𝑙𝑢𝑚𝑛𝑠 = 3 𝑅𝑜𝑤𝑠
>> X2 = B*A 1 𝑟𝑜𝑤𝑠 1 𝑐𝑜𝑙𝑢𝑚𝑛𝑠

The size of product Matrix


1×1
Challenge
Question: Compute 𝑌1, 𝑌2 and 𝑌3 if the value for 𝑥1, 𝑥2 and 𝑥3 are 1.3,
2.7 and 1.02 respectively.

𝑌1 = −2𝑥1 + 3𝑥2 + 𝑥3 --- Eq.1


𝑌2 = −𝑥1 + 3𝑥2 + 3𝑥3 --- Eq.2
𝑌3 = 2𝑥1 − 𝑥2 + 𝑥3 --- Eq.3

Hint: Create MATRIX equation by using Eq1, Eq2 and Eq3.


𝑌1 −2 3 1 𝑥1
𝑌2 = −1 3 3 𝑥2
𝑌3 2 −1 1 𝑥3
(3x1) (3x3) (3x1)

𝑌 =𝐴∗𝑋
What if you want to square each element of M?

2 3 7 22 32 72 2∗2 3∗3 7∗7


𝑀= 0 8 3 𝑁 = 02 82 32 OR 𝑀 = 0∗0 8∗8 3∗3
82 42 12 8∗8 4∗4 1∗1
8 4 1
Answer:
>> M = [2 3 7;0 8 3;8 4 1], N = M.^2 >> M = [2 3 7;0 8 3;8 4 1], N = M.*M

Note: The . preceding the ^ operator signifies that the


operation is to be carried out element by element.

Also known as “array operations” which referred as


element-by-element operations.
Use of Built-In Functions
>> help elfun
Question

Compute values of x, and y for t = 0 to 6π with t = π.


𝑥 = 𝑡 cos(6𝑡)
𝑦 = 𝑡 sin(6𝑡)

Try it yourself !!!


>> dt = pi ,t = 0:dt:6*pi
>> x = t.*cos(6*t)
>> y = t.*sin(6*t)
Challenge

The following equation can be used to compute values of y as a function of x:

𝑦 = 𝑏𝑒 −𝑎𝑥 sin(𝑏𝑥)(0.012𝑥 4 − 0.15𝑥 3 + 0.075𝑥 2 + 2.5𝑥)

where a and b are parameters. Write the equation for implementation with
MATLAB, where a = 2, b = 5, and x is a vector holding values from 0 to π/2 in
increments of x = π/40. In addition, compute the vector where each element
holds the square of each element of y. Combine x, y, and z into a matrix w,
where each column holds one of the variables, and display w (short format).
End of LAB #1
Numerical & Computing
Methods / Chemical Engineering
Laboratory III
LAB #2
LAB #2
• Script m-files
• Function m-files
The most common way to operate MATLAB is by
entering commands one at a time in the command
window.
M-FILES
• M-files provide an alternative way
• An M-file consists of a series of
statements that can be run all at once.
• Such files are stored with a .m extension.
• M-files come in two flavours:
1. script files
2. function files.

Edit window
Used to create and edit M-files.
Script Files
• A script file is merely a series of MATLAB commands that are saved on
a file.
• They are useful for retaining a series of commands that you want to
execute on more than one occasion.
• The script can be executed by typing the file name in the command
window or by
• invoking the menu selections in the edit window: Debug  Run. OR
F5
Exercise 1
Develop a script file to compute the velocity of the free-falling bungee
jumper at t = 12 for the case where the initial velocity is zero.
Solution
• Open the editor with the menu selection: File, New, M-file.
• Type in the following statements to compute the velocity of the free-
falling bungee jumper at a specific time

• Save the file as Lab3Ex1.m. Return to the command window and type
>> Lab3Ex1
Function Files
• Function files are M-files that start with the word function.
• In contrast to script files, they can accept input arguments and return
outputs.
Exercise 2
Compute the velocity of the free-falling bungee jumper (Exercise 1) but now
use a function file for the task.
Solution
• Type the following statements in the file editor:

• Save the file as Lab3Ex2.m.


• To invoke the function, return to the command window
and type in
>> Lab3Ex2(12,68.1,0.25)
Try It Yourself!!!
>> velocity = Lab3Ex2(12,68.1,0.25);
>> fprintf('The velocity is %8.4f m/s\n', velocity)

%a.bc
a - minimum output width
b - number of digits after decimal point
c - Format Code
Challenge

The standard normal probability density function is a bell-shaped curve that can be
represented as:
1 −𝑧 2
𝑓 𝑧 = 𝑒 2
2𝜋

Use MATLAB to create user-define function and determine for several points of z
from z = −5 to 5.
LAB #2
• Relational and logical operator
• Iterations and Conditional statements
Programming Statements and Flow Control
These can be divided into:

1. Decisions (or Selection).


The branching of flow based on a decision.

2. Loops (or Repetition).


The looping of flow to allow statements to be repeated.

3. Switch (or Case Selection)


Execute one of several groups of statements
1. Decisions Basic Code:

if expression
Do statements 1
else
Do statements 2
end

Example:

Use MATLAB to solve this function by using if-else


approaches:
−𝟐𝒙, 𝒙<𝟎
𝒇 𝒙 =
𝟐𝒙, 𝒙≥𝟎
Decisions
𝑥= 1 Basic Code:

if expression
Do statements 1
𝑥<0 else
Do statements 2
end

Solution:
−2𝑥 2𝑥

𝑜𝑢𝑡𝑝𝑢𝑡 = 2
2. Loops
Basic Code:

while expression
statements
end

Example:

Use MATLAB to solve this function by using for approaches:


𝟑

𝒇 𝒙 = (𝒙 + 𝟏)
𝒙=𝟏

= 𝒙+𝟏 𝟏 + 𝒙+𝟏 𝟐 + 𝒙+𝟏 𝟑


Loops
𝑥= 1 Basic Code:
𝐴𝑛𝑠 = 0
while expression
statements
end

Solution:

𝑓= 𝑥 + 1 f = @(x) x + 1;
𝐴𝑛𝑠 = 𝐴𝑛𝑠 + 𝑓 Answer = 0;
for x = 1:3
Answer = Answer + f(x);
end
Answer
𝐴𝑛𝑠
3. Switch Basic Code:

switch switch_expression
case case_expression
statements
case case_expression
statements
...
otherwise
statements
end

Example:

Use MATLAB to solve this function by using switch


approaches:
𝒔𝒊𝒏 𝒙 , 𝒙 = −𝟏
𝒄𝒐𝒔(𝒙), 𝒙=𝟎
𝒇 𝒙 =
𝒕𝒂𝒏 𝒙 , 𝒙=𝟏
𝒄𝒐𝒔 𝒙 + 𝒔𝒊𝒏 𝒙 , 𝒙 ≠ −𝟏, 𝟎, 𝟏
Basic Code:
Switch switch switch_expression
case case_expression
x=? statements
case case_expression
statements
x = -1 output = sin(x) ...
otherwise
statements
x=0 output = cos(x) end

Solution:
x=1 output = tan(x)

output = cos(x) + sin(x)

output
Challenge

Develop an M-file function that is passed a numeric grade from


0 to 100 and returns a letter grade according to the scheme:

In addition, the function must able to displays an error


message and terminates in the event that the user enters a
value of score that is less than zero or greater than 100.
End of LAB #2
Numerical & Computing
Methods / Chemical Engineering
Laboratory III
LAB #3
LAB #3
• Importing data
• Plotting and customisation
Plotting graphs
Available Plot Formats
plot(x,y) Plot the vector x versus the vector y
semilogx(x,y) Plot the vector x versus the vector y
The x-axis is log10, y-axis is linear
semilogy(x,y) Plot the vector x versus the vector y
The x-axis is linear, y-axis is log10
loglog(x,y) Plot the vector x versus the vector y
Both are log10 axes.

Function for Customized Plots


title(‘Text’) Put ‘Text’ at the top of the plot
xlabel(‘TextX’) Label the x-axis ‘TextX’
ylabel(‘TextY’) Label the y-axis ‘TextY’
subplot(row,col,no) Subdivides the plot in the Figure
grid Draws grid line
legend(‘M’,’N’,’K’) Add legend for M, N, & K profiles
Example 1:

Use MATLAB to plot Temperature vs Distance from the following table:

Temperature, K 272.07 274.75 271.60 273.20 273.78 272.11 273.43 272.78 273.56
Distance, m -20 -15 -10 -5 0 5 10 15 20

Solution:
Plotting graphs
Step 1: Prepare dataset Starting value Final value

>> t = 1:0.5:10; x = [xi ∶ dx ∶ xf ]


>> y1 = 2*t.^2 + 2*t + 9;
>> y2 = 3*t.^2 + 0.6*t + 0.1; increment

Step 2: Now create plot


y1 vs t, and y2 vs t together

>> plot(t,y1,t,y2)
Step 3: Add title and axis label

>> title(‘Quadratic plots’)


>> xlabel(‘The x-axis label, t’)
>> ylabel(‘The y-axis label, y’)
Step 4: Add legend and grid

>> legend(‘y1’,’y2’)
>> grid
Specifiers for colors, symbols, and line types.
Example 2:

Use MATLAB to plot Temperature vs Distance and Pressure vs Distance from the following table:
Note: The Figure must follows exactly as per solution

Distance, m -20 -15 -10 -5 0 5 10 15 20


Pressure, kPa 372.58 376.25 371.93 374.12 374.92 372.63 374.44 373.55 374.62
Temperature, K 272.07 274.75 271.60 273.20 273.78 272.11 273.43 272.78 273.56
Challenge

The butterfly curve is given by the following parametric equations:

𝑡
𝑥 = sin 𝑡 𝑒 cos 𝑡 − 2 cos 4𝑡 − sin5
12

cos 𝑡 5
𝑡
𝑦 = cos 𝑡 𝑒 − 2 cos 4𝑡 − sin
12
Fig. Multicolour butterfly curve

Generate values of x and y for values of t from 0 to 100 with dt = 1/16. Construct plots of
(a) x and y versus t
(b) y versus x.

Use subplot to stack these plots vertically and make the plot in (b) black square. Include titles and axis
labels on both plots and a legend for (a). For (a), employ a dotted line for y in order to distinguish it from x.

Create multicolour for butterfly curve as in the example.


LAB #3
• Curve fitting (using built-in function and Newton’s divided-difference /Lagrange)
Curve Fitting Method
TWO general approaches for curve fitting that are:

1. LEAST-SQUARES REGRESSION
where a significant degree of error or “scatter” the strategy is to derive a
single curve that represents the general trend of the data.

2. INTERPOLATION
The curves that pass directly through each of the points. Where, the
estimation of values between well-known discrete points.
Three attempts to fit a “best” curve
through five data points
1. Least-squares regression
Three attempts to fit a “best” curve
through five data points
2. Linear interpolation
Three attempts to fit a “best” curve
through five data points
3. Curvilinear interpolation
Exercise 1
Wind tunnel experiment to measure how the force
of air resistance depends on velocity
Table: Experimental data for force (N) and velocity (m/s) from a wind tunnel experiment.

Q. Plot Force vs velocity


1. SOLVING CURVE FITTING PROBLEM
WITH MATLAB
“polyfit” build-in function is direct solution to finds
the coefficients of a polynomial p(x) of degree n

>> P = polyfit(x,y,n)

returns the coefficients for a polynomial p(x)


i.e. P = [an an-1 an-2 ... a0]

𝑦 𝑥 = 𝑎𝑛 𝑥 𝑛 + 𝑎𝑛−1 𝑥 𝑛−1 + 𝑎𝑛−2 𝑥 𝑛−2 + … + 𝑎0 𝑥 0


EVALUATE POLYNOMIAL

“polyval” build-in function is direct solution to


evaluate a polynomial Y of degree N.
Y = P(1)*X^N + P(2)*X^(N-1) + ... + P(N)*X + P(N+1)

>> Y = polyval(P,X)

returns the value of a polynomial Y evaluated at X


Exercise 2
The following data for the density of
nitrogen gas versus temperature come
from a table that was measured with high
precision. Use first- through fifth-order
polynomials to determine the correlation
of density over temperature, 𝜌 = 𝑓(𝑇)

Table 1. Experimental data


T, [K] 200 250 300 350 400 450
Density,
26 16.415 5.375 3.5 2.015 2.54
[kg/m3]

Hint:
1. Plot density vs temperature
2. Use ‘polyfit’ function to find the correlation for n = 1,2..5
Try It Yourself!!!
Q1. Fit a cubic polynomial to the following data:

X 3 4 5 7 8 9 11 12
y 1.6 3.6 4.4 3.4 2.2 2.8 3.8 4.6

Determine the coefficient of the polynomial

Q2. The following data were gathered to determine the relationship between
pressure and temperature of a fixed volume of 1 kg of nitrogen. The volume is 10
m3 .

T oC -40 0 40 80 120 160


P, N/m2 6900 8100 9350 10500 11700 12800
Employ the ideal gas law pV = nRT to determine R on the basis of these data.
Note: T must be expressed in kelvins.
Curve Fitting Method
TWO general approaches for curve fitting that are:

1. LEAST-SQUARES REGRESSION
where a significant degree of error or “scatter” the strategy is to derive a
single curve that represents the general trend of the data.

2. INTERPOLATION
The curves that pass directly through each of the points. Where, the
estimation of values between well-known discrete points.
1. Linear Interpolation
Is the simplest form of interpolation, connecting two data points
with a straight line.
𝑓1 𝑥 − 𝑓 𝑥0 𝑓 𝑥1 − 𝑓 𝑥0
=
𝑥 − 𝑥0 𝑥1 − 𝑥0
𝑓 𝑥1 − 𝑓 𝑥0
𝑓1 𝑥 = 𝑓 𝑥0 + 𝑥 − 𝑥0
𝑥1 − 𝑥0

𝑓1 𝑥 = 𝑏0 + 𝑏1 𝑥 − 𝑥0

22
Example #1
Problem statement (textbook 18.1)
Estimate the natural logarithm of 2 using linear
interpolation as information given below;
a. Interpolating between ln(1) = 0 and ln(6) = 1.791759
b. Interpolating between ln(1) = 0 and ln(4) = 1.386294

Solution 𝑓 𝑥1 − 𝑓 𝑥0
𝑓1 𝑥 = 𝑓 𝑥0 + 𝑥 − 𝑥0
x f(x) 𝑥1 − 𝑥0
1 0
1.791759 − 0
2 𝑓1 𝑥 = ? 𝑓1 2 = 0 + 2−1
6−1
6 1.791759
= 0.3583519
a. Interpolating between ln(1) = 0 and ln(6) = 1.791759
x f(x) 1.386294 − 0
1 0 𝑓1 2 = 0 + 2−1
4−1
2 𝑓1 𝑥 = ?
= 0.4620981
4 1.386294

Result
Case a: f(2) = 0.35835
Case b: f(2) = 0.4621
True value: f(2) = 0.69315

Relative error
Case a, E = 48.30%
Case b, E = 33.3334%

example1.m
2. Quadratic Interpolation
If three data points are available, the estimate is improved
by introducing some curvature into the line connecting the
points.
𝑓2 𝑥 = 𝑏0 + 𝑏1 𝑥 − 𝑥0 + 𝑏2 𝑥 − 𝑥0 𝑥 − 𝑥1

A simple procedure can be used to determine the values of


the coefficients.
𝑏0 = 𝑓 𝑥0
𝑓 𝑥1 − 𝑓 𝑥0
𝑏1 =
𝑥1 − 𝑥0
𝑓 𝑥2 − 𝑓 𝑥1 𝑓 𝑥1 − 𝑓 𝑥0

𝑥2 − 𝑥1 𝑥1 − 𝑥0
𝑏2 =
𝑥2 − 𝑥0 26
Example #2
Problem statement (textbook 18.2)
Estimate the natural logarithm of 2 using quadratic
interpolation for 3 points data.
Given ln(1) = 0, ln(4) = 1.386294, and ln(6) = 1.791759

Solution
𝑓2 𝑥 = 𝑏0 + 𝑏1 𝑥 − 𝑥0 + 𝑏2 𝑥 − 𝑥0 𝑥 − 𝑥1
x f(x)
1 0 𝑏0 = 0
2 𝑓1 𝑥 = ?
4 1.386294 1.386294 − 0
𝑏1 = = 0.4620981
6 1.791759 2−0
Estimate the natural logarithm of 2 using quadratic
interpolation for 3 points data.
1.791759 − 1.386294 1.386294 − 0

𝑏2 = 6 − 4 4−1 = −0.0518731
6−0
Thus, for x = 2
𝑓2 𝑥 = 0 + 0.4620981 𝑥 − 1 − 0.0518731 𝑥 − 0 𝑥 − 4

Result
Approx. f(2) = 0.56584
True f(2) = 0.69315
Relative error, E = 18.366%

example2.m
General Form of Newton’s Interpolating Polynomials,
nth order
𝑓𝑛 𝑥 = 𝑓 𝑥0 + 𝑥 − 𝑥0 𝑓 𝑥1 , 𝑥0 + 𝑥 − 𝑥0 𝑥 − 𝑥1 𝑓 𝑥2 , 𝑥1 , 𝑥0
+ ⋯ + 𝑥 − 𝑥0 𝑥 − 𝑥1 … 𝑥 − 𝑥𝑛−1 𝑓 𝑥𝑛 , 𝑥𝑛−1 , … , 𝑥0
Given,
𝑓 𝑥𝑖 − 𝑓 𝑥𝑗
𝑓 𝑥𝑖 , 𝑥𝑗 =
𝑥𝑖 − 𝑥𝑗
𝑓 𝑥𝑖 , 𝑥𝑗 − 𝑓 𝑥𝑗 , 𝑥𝑘
𝑓 𝑥𝑖 , 𝑥𝑗 , 𝑥𝑘 =
𝑥𝑖 − 𝑥𝑘

𝑓 𝑥𝑛 , 𝑥𝑛−1 , … , 𝑥1 − 𝑓 𝑥𝑛−1 , 𝑥𝑛−2 , … , 𝑥0


𝑓 𝑥𝑛 , 𝑥𝑛−1 , … , 𝑥1 , 𝑥0 =
𝑥𝑛 − 𝑥0

Note: Bracketed function evaluations are finite divided differences


Example #3
Problem statement (textbook 18.3)
Estimate the natural logarithm of 2 using nth order
polynomial interpolation
Given ln(1) = 0, ln(4) = 1.386294, ln(5) = 1.609438,
and ln(6) = 1.791759
Solution,
x f(x) n=3
1 0 𝑓3 𝑥 =
2 𝑓1 𝑥 = ? 𝑓 𝑥0 +
4 1.386294
𝑥 − 𝑥0 𝑓 𝑥1 , 𝑥0 +
5 1.609438
𝑥 − 𝑥0 𝑥 − 𝑥1 𝑓 𝑥2 , 𝑥1 , 𝑥0 +
6 1.791759
𝑥 − 𝑥0 𝑥 − 𝑥1 𝑥 − 𝑥2 𝑓 𝑥3 , 𝑥2 , 𝑥1 , 𝑥0
Table: Graphical depiction of the recursive nature of finite divided differences

𝑓 𝑥1 − 𝑓 𝑥0
𝑓 𝑥1 , 𝑥0 =
𝑥1 − 𝑥0
𝑓 𝑥2 , 𝑥1 =?
𝑓 𝑥3 , 𝑥2 =?
𝑓 𝑥2 , 𝑥1 − 𝑓 𝑥1 , 𝑥0
𝑓 𝑥2 , 𝑥1 , 𝑥0 =
𝑥2 − 𝑥0
𝑓 𝑥3 , 𝑥2 , 𝑥1 = ?
𝑓 𝑥3 , 𝑥2 , 𝑥1 − 𝑓 𝑥2 , 𝑥1 , 𝑥0
𝑓 𝑥3 , 𝑥2 , 𝑥1 , 𝑥0 =
𝑥3 − 𝑥0
Estimate the natural logarithm of 2 using 3rd order
polynomial interpolation
𝑓3 𝑥
= 0 + 0.4620981 𝑥 − 1
− 0.05187311 𝑥 − 1 𝑥 − 4
+ 0.007865529 𝑥 − 1 𝑥 − 4 𝑥 − 5

Result
Approx. f(2) = 0.62877
True : f(2) = 0.69315
Relative error, E = 9.288%

example3.m
How good is the interpolation?
Refer to lecture slide titled “Sources of Errors in Numerical
Methods”

• Absolute error: 𝑒𝑟𝑟𝑜𝑟 = 𝑌𝑐𝑜𝑚𝑝𝑢𝑡𝑒 − 𝑌𝑡𝑟𝑢𝑒

𝑌𝑐𝑜𝑚𝑝𝑢𝑡𝑒 − 𝑌𝑡𝑟𝑢𝑒
• Relative error: 𝑒𝑟𝑟𝑜𝑟 =
𝑌𝑡𝑟𝑢𝑒

However in the real world, true solution is very difficult to


obtain. The accuracy of interpolation result can only be justified
when we validate the approximation function with the real
process otherwise the result can be questioned.
End of LAB#3
Numerical & Computing
Methods / Chemical Engineering
Laboratory III
LAB #4
Use MATLAB to find the root of equation
1. Graphical method
2. Increment Search method
3. Bisection method
4. False position
5. Newton-Raphson
6. MATLAB Built-In Functions
ROOTS IN ENGINEERING AND SCIENCE
A simple method for obtaining an estimate of the root of
the equation 𝑓(𝑥) = 0 is to make a plot of the function
and observe where it crosses the x axis.

This point, which represents the x value for which f (x) =


0, provides a rough approximation of the root.

Let: 𝑔𝑚 𝑔 𝑐𝑑
𝑓 𝑚 = tanh 𝑡 −𝑣 𝑡
𝑐𝑑 𝑚

𝑓 𝑥 = 0, 𝑡ℎ𝑒𝑛 𝑥 = ?

Note: Now we can see that the answer to the problem is the value of m that
makes the function equal to zero. Thus, we call this a “roots” problem
Graphical Method
Let: 𝑓 𝑚 = 𝑔𝑚
tanh
𝑔 𝑐𝑑
𝑡 −𝑣 𝑡 ;
𝑐𝑑 𝑚

Q. Determine the mass (root) when the 𝑓(𝑚) = 0


𝑓(𝑥) = 𝑥 3 + 3𝑥 2 − 6𝑥 − 8
%Define anonymous function
f = @(x) x.^3 + 3*x.^2 - 6*x - 8;

%Create vector x
xmin = -5; xmax = 3; ns = 10000;
x = linspace(xmin,xmax,ns);
%Compute vector f
y = f(x);
%Plot f vs x
plot(x,y);
1. Increment Search method
2. Bisection method

is a variation of the incremental


search method in which the
interval is always divided in half.

Code: Bisectionmethod.m
3. False position
a.k.a linear interpolation method

Code: FalsePositionMethod.m
4. Newton-Raphson
%Newton-Raphson
%Define anonymous function
f = @(x) x.^3 + 3*x.^2 - 6*x - 8;
df = @(x) 3*x.^2 + 6*x - 6;
xr = 0.1; %Initial guess
es = 0.0001; maxit = 50; iter = 0;
while (1)
xrold = xr;
xr = xr - f(xr)/df(xr);
iter = iter + 1;
if xr ~= 0,
ea = abs((xr - xrold)/xr) * 100;
end
if ea <= es | iter >= maxit,
break,
end
end
root = xr
MATLAB Built-In Function
to solve roots problem

fzero - Find root of continuous function of one variable.


>> f = @(x) x^3 + 3*x^2 - 6*x - 8; %anonymous function
>> x0 = 0.5; %Finding the zero of the function near x0.
>> x = fzero(f,x0)

roots - Polynomial roots


The polynomial 𝑃 = 𝑥 3 − 6𝑥 2 − 72𝑥 − 27 is represented in MATLAB software as

>> P = [1 -6 -72 -27];

The roots of this polynomial are returned in a column vector by

>> r = roots(P)
Challenge #1
Let: 𝑓 𝑚 = 𝑔𝑚
tanh
𝑔 𝑐𝑑
𝑡 −𝑣 𝑡 ;
𝑐𝑑 𝑚

Q. Determine the mass (root) when the 𝑓(𝑚) = 0


Challenge #1: solution
Challenge #2
In a chemical engineering process, water vapor (H2O) is heated to sufficiently
high temperatures that a significant portion of the water dissociates, or splits
apart, to form oxygen (O2) and hydrogen (H2):

If it is assumed that this is the only reaction involved, the mole fraction x of H2O
that dissociates can be represented by

where K is the reactions equilibrium constant and pt is the total pressure of the
mixture. If 𝑝𝑡 = 3 atm and 𝐾 = 0.05, determine the value of x.
Challenge #2: solution

Answer
Challenge #3
The Redlich-Kwong equation of state is given by

where R = the universal gas constant , 0.518 kJ/(kg K), T = absolute


temperature (K), p = absolute pressure (kPa), and v = the volume of a kg of gas
(m3/kg). The parameters a and b are calculated by

where pc = 4600 kPa and Tc = 191 K.

As a chemical engineer, you are asked to determine the amount of


methane fuel that can be held in a 3-m3 tank at a temperature of −40 oC
with a pressure of 6500 kPa. Use a root-locating method of your choice
to calculate v and then determine the mass of methane contained in the
tank.
Challenge #3: solution

Answer
Challenge #4

The volume of liquid V in a hollow horizontal cylinder of radius r


and length L is related to the depth of the liquid h by

Determine h given r = 2 m, L = 5 m3, and V = 8 m3.


Challenge #4: solution

Answer
End of LAB#4
Numerical & Computing
Methods / Chemical Engineering
Laboratory III
LAB #5
Use MATLAB to solve linear equation

Topic covers:
1. Graphical method
2. Gauss Elimination
3. LU Factorization
Sol. of Algebraic Eq.
Graphical method
Q. Solve graphically and check your results by substituting them back into the equations.

3𝑥1 + 2𝑥2 = 18

−𝑥1 + 2𝑥2 = 2

A.
Gauss Elimination
without pivoting
Gauss Elimination
with pivoting
SOLVING LINEAR ALGEBRAIC EQUATIONS
WITH MATLAB
Direct solution to solve systems of linear algebraic
equations.
• to use backslash, or left-division, operator as in
>> x = A\b
• to use matrix inversion:
>> x = inv(A)*b
Try It Yourself!!!
Q1. Compute x1, x2 and x3

150 −100 0 𝑥1 588.6


−100 150 −50 𝑥2 = 686.7
0 −50 50 𝑥3 784.8

Q2. Write the following equation in matrix form and determine the unknowns

50 = 5𝑥3 − 6𝑥2

2𝑥2 + 7𝑥3 + 30 = 0

𝑥1 − 7𝑥3 = 50 − 3𝑥2 + 5𝑥1

Q3. Write the following equation in matrix form and determine the unknowns

3𝑥1 + 2𝑥2 = 18

−𝑥1 + 2𝑥2 = 2
LU Factorization with MATLAB
Given:
𝐴 {𝑥} = 𝑏
We can rearrange: LU factorization step.
1. [A] is factored or decomposed
𝐴 𝑥 − 𝑏 =0
into lower [L] and upper [U]
We know: triangular matrices.
𝐿 𝑈 = 𝐴 and let, 𝑏 = 𝐿 𝑑 2. Substitution step. [L] and [U]
are used to determine a solution
Thus, {x} for a right-hand side {b}.
𝐿 𝑈 𝑥 − 𝐿 𝑑 =0 MATLAB uses lu built-in
function to get LU of [A].
𝑥 = 𝑖𝑛𝑣 𝑈 𝑑
Where, >> [L,U] = lu(A)
𝑑 = 𝑈 𝑥
Q. Determine the unknowns by using LU Factorization method
0 −6 5 𝑥1 50
0 2 7 𝑥2 = −30
−4 3 −7 𝑥3 50
Challenge

Determine the solution of the simultaneous equations by using


the following method:

−3𝑥1 + 12𝑥2 = 9
10𝑥1 − 2𝑥2 = 8

1. Graphical Method
2. Gaussian Elimination Method
3. LU Factorization Method

NOTE: Answer should includes m-file code and result.


End of LAB#5
Numerical & Computing
Methods / Chemical Engineering
Laboratory III
LAB #6
Integration & Differentiation
Solution to ODE
1. SOLVING DIFFERENTIATION PROBLEM
WITH MATLAB
MATLAB Function Description
k = polyder(p) Differentiate polynomial analytically
dx = diff(x) Difference and approximate derivative.
[px,py]= gradient(x) numerical gradient of the matrix x

Let:
𝑦 = 3𝑥 4 + 12𝑥 3 − 21𝑥 2 + 18𝑥

Solution for 1st derivative:


𝑑𝑦
= 12𝑥 3 + 36𝑥 2 − 42𝑥 + 18
𝑑𝑥
MATLAB approach:
POLYDER - Differentiate polynomial (Analytical Method).

>> P = [3 12 -21 18 0];


>> k = polyder(P)

returns the derivative coefficients of polynomial and it represent:

𝑑𝑦
= 12𝑥 3 + 36𝑥 2 − 42𝑥 + 18
𝑑𝑥

𝑑𝑦
Q. Determine the gradient at 2,
𝑑𝑥 𝑥=2

>> dydx = polyval(k,2)


Try it yourself
𝑑𝑦
Q. Determine the gradient at 2,
𝑑𝑥 𝑥=2

% Example of diff (Numerical Solution)


f = @(x) 3*x.^4 + 12*x.^3 - 21*x.^2 + 18*x;
x = [1.9 2.1];
y = f(x);
dydx_2 = diff(y)./diff(x)

% Example of gradient (Numerical Solution)


f = @(x) 3*x.^4 + 12*x.^3 - 21*x.^2 + 18*x;
x = [1.9 2.1];
y = f(x);
dydx_2 = gradient(y)./gradient(x)
f = @(x) 3*x.^4 + 12*x.^3 - 21*x.^2 + 18*x;
x = [1.9 2.1];
y = f(x);
subplot(2,1,1)
plot(x,y,'-r*'),hold on
xfcn = linspace(1.8,2.2,100);
yfcn = f(xfcn);
plot(xfcn,yfcn,'-b'),hold off,grid on
ylabel('y'),xlabel('x')

P = [3 12 -21 18 0];
k = polyder(P)
dxfcn = linspace(1.8,2.2,100);
dyfcn = polyval(k,xfcn);
subplot(2,1,2)
plot(dxfcn,dyfcn,'-b'),hold on
dx = (x(2)+x(1))/2;
dydx = diff(y)./diff(x);
plot(dx,dydx,'sr'),hold off,grid on
ylabel('dydx'),xlabel('x')
Challenge
Estimate the derivative at 𝑥 = 0.5 of

𝑓 𝑥 = −0.1𝑥 4 − 0.15𝑥 3 − 0.5𝑥 2 − 0.25𝑥 + 1.2

Q1. Use MATLAB built-in function,


Q2. Use finite-differences at step size of ℎ = 0.25, for:
• Backward
• Centred
• Forward
Challenge

The objective of this problem is to compare second order accurate forward, backward, and centered
finite difference approximations of the first derivative of a function to the actual value of the
derivative. This will be done for

𝑓 𝑥 = 𝑒 −2𝑥 − 𝑥

a) Use calculus to determine the correct value of the derivative at 𝑥 = 2.


b) Develop an M-file function to evaluate the centered finite-difference approximations, starting
with 𝑥 = 0.5 . Thus, for the first evaluation, the x values for the centered difference
approximation will be 𝑥 = 2 ± 0.5 or 𝑥 = 1.5 and 2.5. Then, decrease in increments of 0.1
down to a minimum value of ∆𝑥 = 0.01.
c) Repeat part (b) for the second-order forward and backward differences.
d) Plot the results of (b) and (c) versus x. Include the exact result on the plot for comparison.
End of LAB#6
Numerical & Computing
Methods /Chemical Engineering
Laboratory III
LAB #7
Integration & Differentiation
Solution to ODE
2. SOLVING INTEGRATION PROBLEM WITH
MATLAB
MATLAB Function Description
I = polyint(p,k) Integrate polynomial analytically
I = trapz(x,y) Trapezoidal numerical integration.
computes an approximation of the cumulative integral of Y via
I = cumtrapz(y)
the trapezoidal method (with unit spacing).
I = quad(fun,a,b) Use adaptive Simpson quadrature

Solve the following question:

𝑦= 12𝑥 3 + 36𝑥 2 − 42𝑥 + 18 𝑑𝑥


Answer:
𝑦 = 3𝑥 4 + 12𝑥 3 − 21𝑥 2 + 18𝑥 + 𝐶 Where C is constant of
integration
Limits of integration is specified
𝑏
3 2
𝑦= 12𝑥 + 36𝑥 − 42𝑥 + 18 𝑑𝑥
𝑎
Answer:
𝑦 = 3𝑥 4 + 12𝑥 3 − 21𝑥 2 + 18𝑥 𝑏
𝑎

Let, 𝑃 𝑥 = 3𝑥 4 + 12𝑥 3 − 21𝑥 2 + 18𝑥

𝑦 =𝑃 𝑏 −𝑃 𝑎
Let the limit a and b from 1 to 2 respectively,
𝑦 = 96 − 12

∴ 𝑦 = 84
% Example of polyint (Analytical Solution)
P = [12 36 -42 18];
Pint = polyint(P)
a = 1;b=2;
I_ana = polyval(Pint,b) - polyval(Pint,a)

% Example of trapz (Numerical Solution)


P = [12 36 -42 18];
n = 2;
x = linspace(a,b,n+1);
y = polyval(P,x);
I = trapz(x,y)

% Example of cumtrapz (Numerical Solution)


P = [12 36 -42 18];
n = 2;
x = linspace(a,b,n+1);
y = polyval(P,x);
I = cumtrapz(x,y)

% Example of quad (Numerical Solution)


fcn = @(x) 12*x.^3+36*x.^2-42*x +18;
a = 1; b = 2;
I = quad(fcn,a,b)
Integration_Example2.m
Integration_Example2.m
Challenge
End of LAB#7
Numerical & Computing
Methods / Chemical Engineering
Laboratory III
LAB #8
How much data is "Big Data"?

Michael E Driscoll - Metamarkets 2010


Big Data main characteristics
Volume - Volume describes the amount of data generated by
organizations or individuals.
Velocity - Velocity describes the frequency at which data is generated,
captured and shared.
Variety - Big data means much more than rows and columns. It means
unstructured text, video, audio that can have important impacts on
company decisions – if it’s analysed properly in time.
Example:
1. Twitter produces over 90 million tweets per day.
2. eBay uses two data warehouses at 7.5 petabytes.
Application of Numerical Method for Big Data Analysis

Data is not useful unless it is


processed in way that provides
context and meaning that can
be understood by the right
personnel.”
• —Experts at the NSF Industry/University Cooperative Research Center
Big Data handling

https://doi.org/10.1016/j.ijinfomgt.2014.10.007
Data Management

1. Acquisition and Recording


• Literature
• Database
Database:
• Experiment https://data.dublinked.ie/dataset/brown-bin-
• Survey recycling-waste-collection-in-dublin-city

• Data logger
Data Management

2. Extraction, Cleaning, Annotation


Extraction – Import raw data to workspace and create a matrix variable
for every parameters in the dataset. i.e: par1 = data(:,1), datasetA =
data(:,1,2), etc.

Cleaning – Look for empty or ill defined value then replace/remove as


necessary. i.e: empty cell, negative value for time parameter, etc.

Annotation – Make remark on the parameters suite to the scope of


study. i.e: dependent/independent, objective, constraint, etc.
Data Management

Example: Extraction, Cleaning, Annotation


Extraction
Step 1: Import “data.csv” to MATLAB workspace.
i.e:
Step 2: Identify variable: {‘Week’, ’Year’, ’Weight’, ’Lift’}
i.e:

Cleaning (not required for this example)

Annotation
Step 3: Let Weight as Target variable & Week and Year as input
variables
Data Management

3. Integration, Aggregation and Representation


Integration – Combine the information into set of matrix to ease data
handling. i.e: create ‘mol’ variable for given information of ‘mass and
‘weight’.

Aggregation – Combine the data from different set to create new matrix. To
do this, the field/name of parameter might need to be identical. i.e: create
an overall dataset from 2 existing datasets.

Representation – display an overall data in term of table, figure, photo,


assay, etc. i.e: show figure which contain several temperature profiles over
time
Data Management

Example: Integration, Aggregation and Representation

Integration
Step 4: Add variable ‘Average’

Aggregation (not required for this example)

Representation –
Analysis

4. Modelling and Analysis


Modelling – create a mathematical correlation to represent dataset
according to the objective of the study. In normal case, it requires 1
dependent and at least 1 independent variables.
i.e: Cp(T) = aT3 + bT2 + cT + d, where CP is dependent and T is
independent variable, a,b,c and d is coefficient of the correlation.

Analysis – a detailed examination of the elements/parameters which


use the correlation (from modelling) to understand the data.
i.e: to find the effect of T towards Cp.
Analysis

Example: Modelling and Analysis


Modelling – Let model for year 2010

Analysis –
• Midyear of 2010 shows consistent incline trend.
• Several point can be ignored due to outlier data point, thus need another
correlation for this dataset.
Analysis

5. Interpretation
To understand the meaning of findings
• Concept of idea
• Consistent of data
• Relationship of certain parameters
End of LAB#8

You might also like