LAB 1 - Lab 8 Numerical Analysis Lab
LAB 1 - Lab 8 Numerical Analysis Lab
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.
• >> a = 4
• >> x = 2+i*4
Character
Strings
Arrays, Vectors and Matrices
is a collection of values that are represented
by a single variable name.
Note: The scalars used are actually matrices with one row and one column.
Challenge
𝟑 𝟏. 𝟓 𝟐
𝒙=
𝟎. 𝟏 𝟕 𝟏
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
+ Addition + Addition
- Subtraction - Subtraction
* Multiplication .* Multiplication
/ Division ./ Division
^ Power .^ Power
Try it Yourself !!!
>> x2 = 2/b
1 2 3 × 3 4 5
𝑎(1 × 3) 𝑏(1 × 3)
3 𝑐𝑜𝑙𝑢𝑚𝑛𝑠 ≠ 1 𝑅𝑜𝑤𝑠
𝑌 =𝐴∗𝑋
What if you want to square each element of M?
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:
%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:
if expression
Do statements 1
else
Do statements 2
end
Example:
if expression
Do statements 1
𝑥<0 else
Do statements 2
end
Solution:
−2𝑥 2𝑥
𝑜𝑢𝑡𝑝𝑢𝑡 = 2
2. Loops
Basic Code:
while expression
statements
end
Example:
𝒇 𝒙 = (𝒙 + 𝟏)
𝒙=𝟏
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:
Solution:
x=1 output = tan(x)
output
Challenge
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
>> plot(t,y1,t,y2)
Step 3: Add title and axis label
>> 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
𝑡
𝑥 = 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.
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.
>> P = polyfit(x,y,n)
>> Y = polyval(P,X)
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
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 .
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
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 − 𝑓 𝑥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”
𝑌𝑐𝑜𝑚𝑝𝑢𝑡𝑒 − 𝑌𝑡𝑟𝑢𝑒
• Relative error: 𝑒𝑟𝑟𝑜𝑟 =
𝑌𝑡𝑟𝑢𝑒
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
𝑔 𝑐𝑑
𝑡 −𝑣 𝑡 ;
𝑐𝑑 𝑚
%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
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
>> r = roots(P)
Challenge #1
Let: 𝑓 𝑚 = 𝑔𝑚
tanh
𝑔 𝑐𝑑
𝑡 −𝑣 𝑡 ;
𝑐𝑑 𝑚
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
Answer
Challenge #4
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
Q2. Write the following equation in matrix form and determine the unknowns
50 = 5𝑥3 − 6𝑥2
2𝑥2 + 7𝑥3 + 30 = 0
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
−3𝑥1 + 12𝑥2 = 9
10𝑥1 − 2𝑥2 = 8
1. Graphical Method
2. Gaussian Elimination Method
3. LU Factorization Method
Let:
𝑦 = 3𝑥 4 + 12𝑥 3 − 21𝑥 2 + 18𝑥
𝑑𝑦
= 12𝑥 3 + 36𝑥 2 − 42𝑥 + 18
𝑑𝑥
𝑑𝑦
Q. Determine the gradient at 2,
𝑑𝑥 𝑥=2
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
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𝑥 − 𝑥
𝑦 =𝑃 𝑏 −𝑃 𝑎
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)
https://doi.org/10.1016/j.ijinfomgt.2014.10.007
Data Management
• Data logger
Data Management
Annotation
Step 3: Let Weight as Target variable & Week and Year as input
variables
Data Management
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.
Integration
Step 4: Add variable ‘Average’
Representation –
Analysis
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