Numerical Methods - Lab Manual-Spring 2017
Numerical Methods - Lab Manual-Spring 2017
College of Engineering
Numerical Methods Lab
Numerical Methods
GENG 300
LAB MANUAL
Prepared by
i
Qatar University
College of Engineering
Numerical Methods Lab
INTRODUCTION TO MATLAB
Definition:
MatLab is a software tool that enables the user to perform many types of calculations and be able
to implement numerical methods. It is operated by entering commands in the command window
and display the results.
As defined by MathWorks
MATLAB® is the high-level language and interactive environment used by millions of engineers and
scientists worldwide. It lets you explore and visualize ideas and collaborate across disciplines
including signal and image processing, communications, control systems, and computational finance
MATLAB Environment:
3. Edit window which is used to create and edit what is called “M-files”
1
Qatar University
College of Engineering
Numerical Methods Lab
2. You can use command window as calculator to start with it, Here are few examples.
3. Note that automatically MatLab assigns the answer to a variable “ans” which you can
use in further calculations.
2
Qatar University
College of Engineering
Numerical Methods Lab
5. If you wish to assign a value to a “variable” in MatLab, all what you have to do is to type:
6. Echo printing: it is a characteristic of MatLab which enables the “reprint” of the value
you have assigned to your variable. It is effective in 2 cases:
7. Echo printing can be suppressed by ending the command line with a semicolon “;” as
shown in figure
8. Note that MatLab treats the variable name in a case sensitive manner, so “a” is not the
same as “A”
3
Qatar University
College of Engineering
Numerical Methods Lab
9. Format commands:
“format long” & “format short” to increase and decrease the decimal places of the value
respectively. See figure below for illustration
>> a = [1 2 3 4 5]
b) Vector: one dimensional arrays. It can be a “row vector” or “column vector” (mostly
used). To enter a row vector no commas or semicolons are introduced between the
numbers as:
>> b = [6 7 8];
4
Qatar University
College of Engineering
Numerical Methods – GENG 300
>>b = [2 4 6 8 10]’
>> A = [1 2 3
456
7 8 9]
5
Qatar University
College of Engineering
Numerical Methods – GENG 300
d) To select elements from an already entered array, use the subscript notation “()” as:
Type “who” to see the variables you have already defined in the opened command window.
6
Qatar University
College of Engineering
Numerical Methods – GENG 300
12. Size of a matrix: in order to get the size of a matrix which helps you know if
the operations performed on the matrices are correct, the size command is used
as shown in figure 1.9.
13. The colon operator: is a tool that is used to create and manipulate arrays.
c. Negative increments can also be used by adding ”-“ sign to the number.
d. The colon operator can also be used to select the individual rows and columns
of a matrix. For example, if a colon is used instead of a certain subscript, the
colon represents the entire row or column.
e. The colon operator can be used as well to “selectively” extract a series of
elements from within an array. Flow up on figure on next page
7
Qatar University
College of Engineering
Numerical Methods – GENG 300
If the “n” is omitted or not specified, MatLab automatically generated 100 points.
8
Qatar University
College of Engineering
Numerical Methods – GENG 300
b. It has the form: logspace (x1, x2, n) which generates “n” logarithmically equally
spaced points between the decades 10x1 and 10x2.
16.
9
Qatar University
College of Engineering
Numerical Methods – GENG 300
^ Exponentiation
- Negation
* / Multiplication and division
\ Left division which applies to matrix
algebra
+ - Addition and subtraction
Exercise 1: define the variables u = 3, a=5;t=6 in MATLAB and perform the following
mathematical operations:
find v=u+at
find S=ut+at2/2
x = u2
y=1/u+sin(x)+ex
Answer:
Note: realize by observing error sign that MATLAB variable is case sensitive.
10
Qatar University
College of Engineering
Numerical Methods – GENG 300
Solution:
11
Qatar University
College of Engineering
Numerical Methods – GENG 300
Exercise 2: find the inner product and outer product of the two vectors: a = [1 2 3 4 5] and b
= [2;4;6;8;10]. (hint: use the * operator).
12
Qatar University
College of Engineering
Numerical Methods – GENG 300
1) a * A
2) A * b
3) A * a (matrices can’t be multiplied if the inner dimensions are
unequal).
4) A * A
5) A/pi
6) A2 (MatLab will apply the simple arithmetic operators in vector-
matrix fashion if possible).
7) A. ^2 (note that the . preceding the ^ operator signifies that
the operation is to be carried out element by element).
17. In order to get back to the last typed line and editing it, press the up-arrow key. You
can use it to get back to any command line you entered by just keep pressing on it. It
is a very useful shortcut for editing commands, for example you can type “b” and
press the
up arrow key and you will get back to the last command beginning with “b”.
13
Qatar University
College of Engineering
Numerical Methods – GENG 300
Exercise : Try to get information of other built-in command using help in MATLAB, as for
example (type: help command name)
14
Qatar University
College of Engineering
Numerical Methods – GENG 300
Enter x and y as row data, then use plot(x,y) command to generate plots. As for example
You need to generate 3-D plot when you have dependent variable and two independent
variables. For example if you want to plot Z as function of x and y
Qatar University
College of Engineering
Numerical Methods – GENG 300
1. Click on the help menu in the command window and explore the different options.
2. Use the “help” command (as discussed in Lab 1) if you know the command or
function name.
3. Use the “lookfor” command to search the MatLab help files for occurrences of text if
you don’t know the name of the command or function. For illustration, type:
Introduction to Lab 2:
As it had been discussed in the Lab1, there are three main windows in MatLab; the
command window at which commands are entered in sequence to operate MatLab, the
graphics window at which plots are presented, and the edit window at which M-files are
created and edited.
After introducing command window and graphics window in previous lab, in Lab
2, the use of edit window is extended to explain how to create and edit M-files and what
are the main uses of M-files.
Qatar University
College of Engineering
Numerical Methods – GENG 300
M - files:
An M-file contains a “series of statements” that can be run all at once in order to
provide different way of performing operations using MatLab. The nomenclature “M-
file” comes from the fact that those files are stored with a (.m) extension.
1. Script file.
2. Function file.
Script files:
A script file mainly consists of a series of MatLab commands that are saved on a
file. It is very beneficial for the sake of retaining a series of commands that can be
executed more than one time and for different objectives.
b. Invoking the menu selections in the edit window: Debug, run (or right click >>
run).
Exercise 1: develop a script file to compute the distance travelled when initial value,
time and acceleration are given
Solution steps:
2. Type the proper statements to calculate the distance with known values of u,a and t.
And if you run the script M file you will get as shown below in command window
Qatar University
College of Engineering
Numerical Methods – GENG 300
Function files:
A function file is an M-file that starts with the word “function”. It differs from script file that it
can accept input arguments and return outputs. The syntax for the function file can be
represented as:
% helpcomments
statements
outvar = value;
The first line of the “helpcomments” is called the “H1” line and it is the line that is
searched by the lookfor command. Because of that; key descriptive words related to
the file must be included on this line.
Exercise 2: develop a function file to compute the distance travelled when initial value,
time and acceleration are given
Solution steps:
1. Creation of the function file as illustrated in figure below
3. To invoke the function at different values, type distance (value of t, value of m, value
of Cd) as you want.
4. To invoke the help comments, simply type: >> help distance in command window.
5. Later on, if you forgot the name of this function, but you remember that it is about
bungee jumping, type in the command window: >> lookfor bungee.
Exercise 3: compute the mean and standard deviation of the vector y = [8 5 10 12 6 7.5
4] using function M-file.
Above function M file can be run to find mean and standard deviation of the above data as below
Important note: because script files have limited utility, function M – files will be the
primary programming tool for our interactive labs. So whenever referred to M – files they
are function M – files.
Input – Output:
Information is passed into function via the argument list and is output via the function’s name.
There are other functions which can be used to enter and display information directly using the
command window. These functions are the “input” function and the “display” function.
The input function prompts the user for values directly from the command window. Its syntax is:
n = input (‘promptstring’)
The function will show the promptstring and will wait for the user to input a value or a string so
it will be assigned for the variable “n”. If the user wants to enter a string instead of value, the
following syntax is used:
n = input (‘promptstring’,’s’)
Qatar University
College of Engineering
Numerical Methods – GENG 300
This function is used to display a value or a string and its syntax is: disp (value/variable/string).
Exercise 4: compute the distance travelled when initial value, time and acceleration are
given (exercise 2) using the input and display functions for input/output.
Structured Programming:
The simplest type of all M – files perform the operations sequentially or line by line. Because
this sequence is highly limiting, MatLab includes statements that allow the program to take non-
sequential path. These statements are classified as:
1. Decisions (or selections) which represents the branching of flow based on a decision.
2. Loops (or repetition) which represents the looping of flow to allow statements to be
repeated (to be discussed in lab 3).
Decisions
1. The “if” structure: allows the user to execute a set of statements if a logical condition is
true. The general syntax is:
if condition
statements
end
By the same way, the ‘if else’ and ‘if elseif’ structures are represented in MatLab:
Qatar University
College of Engineering
Numerical Methods – GENG 300
if condition
statements
else
statements
end
if condition
statements
elseif condition
statements
end
Exercise 7: create a function M –file that asks the student to input his/her name &
grade in numbers to see the overall grade (A, B+, B,…etc).
2. The ‘error’ function which has the syntax: error (message) and can be used for error
trapping by displaying the “message” and terminating the M - file and return to the
Qatar University
College of Engineering
Numerical Methods – GENG 300
command window. For example, if you have identified your variable f = 1/x and you
want to detect the error of dividing by zero, the error function can be implemented in the
M – file itself as shown below.
MatLab allows the user to test more than one logical condition by employing logical
operators. The mostly used expressions are:
Lab session 3
1. Loops
As the name indicates, what loops do is that they perform operations repetitively. Depending on
how the repetitions are terminated; loops come into two forms, the for loop and the while loop:
The “for…end” structure: a “for” loop repeats statements a specific number of times and
its general syntax is:
for j = 10:-1:1
disp (j)
end
Qatar University
College of Engineering
Numerical Methods – GENG 300
While Loop:
The “while” structure: a while loop repeats as long as a logical condition is true and its
general syntax is:
while condition
statements
end
Put in mind that the “statements” between the “while” and the “end” are repeated as long as
the “condition” is true. For a quick example, execute the following using an M-file:
x=8
while x > 0
x = x – 3;
disp (x)
end
The “while…break” structure: the while structure is very useful, but it exits at the
beginning of the structure on a false result which is limiting. In order to overcome this
problem; a special version of the while loop is used with the following syntax:
while (1)
statements
if condition, break, end
statements
end
Qatar University
College of Engineering
Numerical Methods – GENG 300
The “break” is used to terminate execution of the loop if the condition tests true. It can be
placed at the middle of a loop and this is called the “midtest” loop. The “break” can be
added at the beginning (before statements) if required and this is called the “pretest” loop:
while (1)
x = x – 5;
end
Exercise 2: develop a function to compute the quadratic roots of an equation using the
following formula:
√ 4
2
Note that the user must provide the values of a, b, and c.
Qatar University
College of Engineering
Numerical Methods – GENG 300
What we have done so far using MatLab is developing a function for each new equation we want
to analyze. Although this procedure is fine, a better alternative is to design a generic function and
pass the particular equation that the user wants to analyze as an “argument”. In MatLab, such
functions are names as “function functions”.
Anonymous functions:
Ananymous functions allow the user to create a simple function without creating an M – file.
These functions can be defined within the command window with the below syntax:
Where:
Qatar University
College of Engineering
Numerical Methods – GENG 300
fhandle: the function which the user can use to call the function.
arglist: a comma separated list of input arguments to be passed to the function.
expressions: any single valid MatLab expression.
Exercise 3: create the anonymous function f(x) = 4x2 using MatLab and evaluate it for x
= 3.
Qatar University
College of Engineering
Numerical Methods – GENG 300
Function functions are functions that operate on other functions which are passed to it as input
arguments. “passed function” is the function that is passed to the function function. A quick
example is the built-in function “fplot” which plots the graphs of functions, and its syntax is:
Where “fun” is the function being plotted between the x – axis limits specified by “lims” = [xmin,
xmax]. In this case “fun” is the passed functions. What is important to mention is that this function
is “smart” because it automatically analyzes the function and decides how many values to use so
that the plot will exhibit all the function’s features.
Exercise 4: use “fplot” to plot the velocity of the free-falling bungee jumper. Remember
that: m = 68.1 kg, g = 9.81 m/s, Cd = 0.25 and let the plot be for values of ‘t’ between 0
and 12.
Using the above function M file to find average value of a function y=x3+3x2+5
It is important to mention that the program must have access to the function (func) and its first
derivative (dfunc) (can simply be accomplished by the inclusion of user-defined functions to
compute these quantities). For a simple example on using ‘newtraph’ function in root finding,
execute the following in the command window:
function yint=Newtint(x,y,xx)
%Newtint: Newton interpolating polynomial
%yint=Newtint(x,y,xx): Uses an (n-1)-order Newton interpolating polynomial
%based on n data points (x,y) to determine a value of the dependant
%variable (yint) at a give value of the independant variable, xx.
%input:
% x= independant variable
% y= dependant variable
% xx= value of the independant variable at which interpolation is
% calculated
%output:
% yint=interpolated value of dependant variable
%compute the finite divided differences in the form of a difference table
n=length(x);
if length(y)~=n, error('x and y must have same length'); end
b=zeros(n,n);
%assign dependant variables to the first column of b.
b(:,1)=y(:); % the (:) ensures that y is a column vector
for j=2:n
for i=1:n-j+1
b(i,j)=(b(i+1,j-1)-b(i,j-1))/(x(i+j-1)-x(i));
end
end
%use the finite divided differences to interpolate
xt=1;
yint=b(1,1);
for j=1:n-1
xt=xt*(xx-x(j));
yint=yint+b(1,j+1)*xt;
end
1. 2x3-6x-4=0
2. x2-ex+x3=0
Solution:
Qatar University
College of Engineering
Numerical Methods – GENG 300
Note: Please observed that in order to get more than one root for same equation you
have to have to run the function file with different guess value.
Qatar University
College of Engineering
Numerical Methods – GENG 300
3. 2x3-6x-4=0
4. x2-ex+x3=0
solution:
Please note that in order to get the other poosible roots you have to run the M
file again with different bracket (xlower & xupper)
Qatar University
College of Engineering
Numerical Methods – GENG 300
The ‘fzero’ function in MatLab is designed to find the real root of a single equation. The syntax
of this function is:
Where ‘function’ is the name of the function being evaluated and x0 is the initial guess. In case
there are two guesses that bracket a sign change, these guesses can be passes as a vector:
If the user is dealing with a case where a single real root must be determined for a polynomial,
then some techniques such as bisection and the Newton – Raphson method can be used easily.
However, if the user desires to get all roots real and complex, then these simple techniques will
not be of much help.
Fortunately, MatLab has an excellent built-in capability which is the ‘roots’ function. The
general syntax of this function is:
x = roots (c)
Where ‘x’ is a column vector containing the roots, and ‘c’ is a row vector containing the
polynomial’s coefficients. Note that if for example the polynomial is:
Then a special matrix can be constructed by using the coefficients from the right hand
side as the first row and with 1’s and 0’s written for the other rows as shown in equation
6.13 in your text book.
This formed matrix is called the polynomial’s companion matrix. It has the useful
property that its ‘’eigenvalues’’ are the roots of the polynomial.
Important note about the ‘roots’ function: the roots function in MatLab has an inverse
function called ‘poly’, which when passed the values of the roots, will return the
polynomial’s coefficients. Its syntax is:
c = poly (r)
Qatar University
College of Engineering
Numerical Methods – GENG 300
Where ‘r’ is a column vector containing the roots and ‘c’ is a row vector containing the
polynomial coefficients.
In order to evaluate the polynomial at a certain value of the independent variable, the
following syntax can be used:
polyval (a, xi)
Where ‘a’ is the row vector that contains the polynomial coefficients and ‘xi’ is the value of
independent variable that the user wants to compute the polynomial at.
Solution:
f=[1 -2 1 -3];
>> roots(f)
ans =
2.1746 + 0.0000i
-0.0873 + 1.1713i
-0.0873 - 1.1713i
Qatar University
College of Engineering
Numerical Methods – GENG 300
Linear Algebra:
Matrices:
So far we have been discussing what are the mostly used tools in Excel and MatLab to
solve single equations. What if there is a need to solve a system of linear equations
simultaneously at which they have “n” number of unknowns? The first thing to make sure of
when trying to solve a system of multiple equations, multiple unknowns is that the number of
equations is equal to the number of unknowns or otherwise this system can’t be solved.
Solving two simultaneous equations is kind of simple to be done by hand, but what if you are
faced with a system of 3 or more, or let’s say 100 unknowns!
In this case the use of “matrices” is practically implemented to manage the process of finding the
unknowns. A “matrix” is a rectangular array of elements represented by a single symbol ‘[A]’.
The matrix consists of ‘m’ rows and ‘n’ columns. When m = n the matrix is called a square
matrix.
a. Symmetric matrix
A=
5 1 2
1 3 7
2 7 8
b. Diagonal matrix
B= 5 0 0
0 3 0
0 0 8
c. Identity matrix
Qatar University
College of Engineering
Numerical Methods – GENG 300
C=
1 0 0
0 1 0
0 0 1
D= 1 2 3
0 5 6
0 0 8
E=
1 0 0
1 5 0
1 2 8
Matrix operations:
There are different operations that can be performed on matrices, so let us just go over them
quickly:
b. Multiplication
c. Inverse of a matrix
d. Identity matrix
e. Size of a matrix
Qatar University
College of Engineering
Numerical Methods – GENG 300
f. Augmentation of 2 matrices
g. Determinant of a matrix
Imagine that these types of operations that take so much time to be completed by hand
calculation (special for large size matrices) can be easily performed using our powerful tool
“MatLab”.
X = [8 6 9]
Y = [-5 8 1]
Z = [4 8 2]
[A]{x} = {b}
Where:
To obtain the solution of this system using MatLab can be found using:
1. x = A\b
2. x = inv (A) *b
Qatar University
College of Engineering
Numerical Methods – GENG 300
Exercise 5: use Naïve Gauss elimination method in MatLab to solve the following
system of linear equations:
LU Factorization:
The idea of the LU factorization is to be able to decompose matrix [A] into two triangular
matrices: the upper triangle matrix [U] and the lower triangle matrix [L].
[A] = [L][U]
Recalling that:
[A]{x} = {b}
[U]{x} = {d}
[L]{d} = {b}
Factorization can be used to solve a system of linear equations according to the following steps:
Exercise 7: use MatLab to compute the LU factorization and find the solution for the
following system of linear equations:
Qatar University
College of Engineering
Numerical Methods – GENG 300
Cramer’s rule:
The Cramer’s rule and the concept of Matrix “determinant” can be used to solve system of
linear equations (for a small number of equations). The hand calculations of this method is kind
of heavy and can be manageable for up to a 3x3 matrix, however, for more than 3 unknowns then
the M-file of this function can be called in MatLab to find the solution easily and within a short
period of time.
In order to solve a system of linear equations using Cramer’s rule in MatLab, the following steps
can be followed:
To calculate x1:
x1=det(A)/D
Qatar University
College of Engineering
Numerical Methods – GENG 300
Exercise 1: use Cramer’s rule with MatLab to solve the following system of linear
equations:
Qatar University
College of Engineering
Numerical Methods – GENG 300
Gauss Seidel:
Guess Seidel is one of the available methods which can be used to solve a system of linear
equations. In order to implement this method in MatLab, you must have the GaussSeidel M-file
which is shown in the below figure.
Qatar University
College of Engineering
Numerical Methods – GENG 300
In order to use this method along with the M-file, the following steps are followed:
Exercise : use GaussSeidel with MatLab to solve the following system of linear
equations:
Qatar University
College of Engineering
Numerical Methods – GENG 300
xi+1 = xi – [J]-1{f}
Using MatLab for this purpose can be into forms:
1. Identifying the range of values of “x” and calculating the Jacobian and the function in the
command window.
2. A better alternative to work out the trials is by using the M-file that computes the
function values and the Jacobian in an iterative fashion. The iterations will continue until
an upper limit of iterations (maxit) or a specified percent relative error (es) is reached.
Qatar University
College of Engineering
Numerical Methods – GENG 300
Exercise 3: use Newton Raphson along with MatLab to find the roots of the following
system of non-linear equations:
x2 + 3x1x22 =57
Qatar University
College of Engineering
Numerical Methods – GENG 300
Solution:
1. Create a function M-file which contains the equation of the function and the Jacobian
as functions of “x”.
2. Call the function using Newton Raphson M-file as shown in the below figure:
Qatar University
College of Engineering
Numerical Methods – GENG 300
Regression
What is Regression?
Mathematical method for determining the best equation that reproduces a data set.
- In a data set (x,y) what is x and y. x is cause and called as independent variable. Whereas
y is effect and called as dependent variable.
- A data set is obtained through experiments and experiment can be conducted only for a
limited data points.
- That’s why regression is performed to come up with a mathematical model which can
predict the value of dependent variable (y) at the all points of x for which experimental
data is not available.
Least Square Regression: A mathematical procedure for finding the best‐fitting curve to a
given set of points by minimizing the sum of the squares of the offsets ("the residuals") of the points
from the curve.
y a 0 a1 x
- “Best” for least-squares regression means minimizing the sum of the squares of the
estimate residuals. For a straight line model, this gives:
n n
S r e i
2
y i a 0 a1xi
2
i1 i1
S r
2 ( y i a 0 a1 xi )
a 0
S r
2 yi a0 a1 xi xi
a1
Rearranging and simplifying above equation lead to following
n a0 xi a 1 yi
xi a 0 xi
2
a 1 xi yi
Above is the system of linear equations with 2 equations and 2 knowns can be presented
in MATRIX form as follows
n xi a0 yi
x i x i y i
2
x i 1
a
a1
n x y x y
i i i i
n x x
2 2
i i
a0 y a1 x
Quantification of Error
Recall for a straight line, the sum of the squares of the estimate residuals
n n
Sr e 2
i y i a 0 a1 x i
2
i1 i1
Sr
sy/ x
n2
- Regression data showing (a) the spread of data around the mean of the dependent data
and (b) the spread of the data around the best fit line:
Qatar University
College of Engineering
Numerical Methods – GENG 300
St ( y y) 2
Coefficient of Determination
• The coefficient of determination r2 is the difference between the sum of the squares of the
data residuals and the sum of the squares of the estimate residuals, normalized by the sum
of the squares of the data residuals:
St Sr
r2
St
• r2 represents the percentage of the original uncertainty explained by the model.
Nonlinear Relationships
Linear regression is predicated on the fact that the relationship between the dependent and
independent variables is linear - this is not always the case.
exponential : y 1e 1 x
power : y 2 x 2
x
saturation - growth - rate : y 3
3 x
exponential : y 1e1 x ln y ln 1 1 x
Transformation Examples
Qatar University
College of Engineering
Numerical Methods – GENG 300
Exercise 1: fit the following data using Microsoft Excel using linear regression:
x y
1 10
2 16.3
3 23
4 27.5
5 31
6 35.6
7 39
8 41.5
9 42.9
10 45
11 46
12 45.5
13 46
14 49
15 50
60
50
40
30
Series1
20
10
0
0 5 10 15 20
Qatar University
College of Engineering
Numerical Methods – GENG 300
2. Right click >> add trend line >> linear as shown in figure 2. Also make sure to check the
boxes corresponding to “display equation on chart” and “display R-squared value on
chart”.
3. As can be shown from the obtained plot, the slope and intercept or (ao and a1) can be
easily obtained by this way. (Remember that for linear regression: y = ao + a1x).
4. Another way to obtain the coefficients (ao and a1) is simple by calculating them using the
following equations:
∑ ∑ ∑
∑ ∑
6. Compare the obtained values of coefficients with the ones obtained from the equation on
the plot.
Note: the same procedure using Excel can be used to fit data in polynomial, exponential, and
power form. For exponential and power forms also linear regression can be used if the
equation was properly transformed into linear form, as an example:
a. Power form: y = axb, can be transformed to linear form as: log(y) = log (a) +b(log(x))
Where: “b” is the slope or “a1” and “log a” is the intercept or “ao”.
b. Exponential form: y = aebx, can be transformed to linear form as: ln(y) = ln(a)+ bx
Qatar University
College of Engineering
Numerical Methods – GENG 300
Calculation of coefficients:
The use of this m-file to calculate the coefficients of the linear regression can be easily done by
just specifying the data points and then call the m-file. For better illustration, follow exercise 4.
As it can be shown from the above solution that the obtained values of the coefficients are in
descending order (a1 then ao).
Note: the same m-file can be used to fit data of exponential order or power order “if they are
transformed into the linear form as was discussed before”.
Qatar University
College of Engineering
Numerical Methods – GENG 300
P = polyfit (x, y, n)
Where “x” and “y” are the vectors of the independent and dependent variables, respectively and
“n” is the order of the polynomial. This function when used returns a vector “P” which contains
the polynomial coefficients (ao, a1, a2,….an) in descending order.
Another built-in function which is available is “polyval” which can be used to compute the value
of the function at certain value of “x” given the polynomial coefficients. Its syntax is:
y = polyval (P, x)
Exercise 3: Resolve exercise 1 using “polyfit” built-in function and calculate the value of
the function @ x = 9.
Qatar University
College of Engineering
Numerical Methods – GENG 300
Polynomial Regression
Therefore, for second order polynomial we got the above system of linear
equations with a0, a1 and a2 unknown. Moreover, above system of equations
can be written in MATRIX form as follows
n x x a yi
2
0
i i
xi a2
x x i i
2 3
x y
i i
x i x x a 3
x i y i
2 3 4 2
i i
Qatar University
College of Engineering
Numerical Methods – GENG 300
Exercise 7: use multiple linear regression in Excel to fit the following set of data:
x1 x2 y
0 0 5
2 1 10
2.5 2 9
1 3 0
4 6 3
7 2 27
Solution: there are different ways to solve this problem, the solution depends on the following
equation:
∑ 1 ∑ 2 ∑
∑ 1 ∑ 1 ∑ 1 2 = ∑ 1
∑ 2 ∑ 1 2 ∑ 2 ∑ 2
The arguments to the function to compute Sr should be the coefficients, the independent
variables, and the dependent variables
y A 1 e x /
x 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 7
y 1.48 1.9 2.07 2.2 2.34 2.38 2.43 2.46 2.47 2.48 2.488 2.49
Solution:
The function M file….
function f = fSSR(a, x, y)
yp = a(1)*(1-exp(-x/a(2)));
f = sum((y-yp).^2);
Interpolation:
Interpolation is used to estimate intermediate values between precise data points. For “n” data
points, there is one and only one polynomial of order (n – 1) that passes through all the points.
The polynomial equation can be represented as follows:
Remember from last session that ‘polyfit’ can be used to perform polynomial regression. In
such application, the number of data points is greater than the number of coefficients being
estimated. Because of that, the least – squares fit line doesn’t necessarily pass through any of
the points, but rather follows the general trend of data.
In case the number of data points = number of coefficients, then “polyfit” performs
interpolation. That means that it returns the coefficients of the polynomial that pass directly
through the data points.
The general syntax is: p = polyfit (x, fx, n) where “n” = order of polynomial.
Qatar University
College of Engineering
Numerical Methods – GENG 300
Exercise 1: determine the coefficients of the parabola f(x) = p1x2 + p2x + p3 that passes
through the following points:
X F(x)
300 0.616
400 0.525
500 0.457
Solution: there are two ways to solve this exercise and find the coefficients using MatLab:
Therefore, the polynomial is f(x) = 0.00000115x2 – 0.001715x + 1.027. In addition, the function
was evaluated at x = 350 and the result is reasonable.
Qatar University
College of Engineering
Numerical Methods – GENG 300
Newton Interpolation:
“Newtint” is an M – file that can be developed to implement Newton interpolation in MatLab.
This M – file is shown in figure 3. The first step is to compute the finite divided differences and
store them in an array. The differences are then used to perform the interpolation.
Qatar University
College of Engineering
Numerical Methods – GENG 300
Exercise 2: employ a second order Newton polynomial to estimate “ln 2” with the
following data points using MatLab:
X F(x)
1 0
4 1.386294
6 1.791759
Qatar University
College of Engineering
Numerical Methods – GENG 300
Exercise 3: employ a third order polynomial to estimate “f(x) at x = 15” using Lagrange
interpolation with the following data points:
X F(x)
‐40 1.52
0 1.29
20 1.2
50 1.09
Where ‘x’ and ‘y’ are vectors containing the values to be interpolated, ‘yi’ is a vector containing
the results of the interpolation as evaluated at the points in the vector ‘xi’, and ‘method’ is the
desired method.
Method Description
nearest Nearest neighbor interpolation which sets a
value of an interpolated point to the value of
the nearest existing data point.
linear Linear interpolation which uses straight lines
to connect the points.
spline Piecewise cubic spline interpolation.
pchip and cubic Piecewise cubic Hermite interpolation.
Note: if the “method” argument is omitted, the default one is linear interpolation where
interp1(x,y,xi) performs one dimensional interpolation where x and y are related as y = f(x)
and xi is some value for which we want to find y(xi) by linear interpolation. This command
will search the x vector to find two consecutive entries between which the desired value
falls. It then performs linear interpolation to find the corresponding value of y.
Exercise 4: use MatLab ‘interp1’ function o fit the following data with (a) linear
interpolation, (b) nearest neighbor interpolation (extra), (c) spline:
X F(x)
0 0
20 20
40 20
56 38
68 80
80 80
84 100
96 100
104 125
110 125
Qatar University
College of Engineering
Numerical Methods – GENG 300
a. Linear Interpolation
Qatar University
College of Engineering
Numerical Methods – GENG 300
Integration:
Integration as can be represented in the below equation is defined as the total value or
summation of f(x)dx over the range x = a to b.
Different presentations and methods used to evaluate the integration using MatLab will be
presented in the upcoming sections.
Z = trapz(x,y)
X F(x)
0 0.2
0.12 1.309729
0.22 1.305241
0.32 1.743393
0.36 2.074903
0.40 2.456
0.44 2.842985
0.54 3.507297
0.64 3.181929
0.70 2.363
0.80 0.232
Qatar University
College of Engineering
Numerical Methods – GENG 300
Note: ‘cumtrapz’ is another function which computes the cumulative integral and it has the
following syntax: z = cumtrapz(x,y).
a. ‘quad’: this particular function uses adaptive Simpson quadrature. It may be more
efficient for low accuracies or no smooth functions.
b. ‘quad1’: this function uses “Lobatto quadrature”. It may be more efficient for high
accuracies and smooth functions.
Where:
Note: if values of ‘tol’ and ‘trace’ are omitted then default values will be used in the
calculations.
1 1
f ( x) s
( x q ) 0.01 ( x r ) 2 0.04
2
Differentiation:
The derivative, which serves as the fundamental vehicle for differentiation, represents the rate
of change of dependent variable with respect to an independent variable. Mathematically, the
derivative of a function can be presented as shown in the below equation:
∆
lim
∆ → ∆
In this section, two MatLab functions will be introduced which can be used easily to find the
derivative in MatLab.
Solution steps:
6. Compute the values for the analytical derivative at a finer level of resolution to
include the plot for comparison as shown in figure 13.
As it can be shown from figure 13, the obtained results from ‘diff’ are close to the analytical
solution of the derivative.
Qatar University
College of Engineering
Numerical Methods – GENG 300
fx = gradient (f)
where ‘f’ is a one dimensional vector of length ‘n’ and ‘fx’ is a vector of length ‘n’ containing
differences based on ‘f’. Same as with the ‘diff’ function, the first value returned is the
difference between the first and the second value. However, for the intermediate values, a
centered difference based on adjacent values is returned:
2
The last value is then computed as the difference between the final two values.
Note that the spacing between the points is assumed to be one. If the vector represents equally
spaced data, the following version divides all the results by the interval and hence returns the
actual values of the derivatives:
fx = gradient (f, h)
Exercise 9: use the ‘gradient’ function to differentiate the same equation of exercise 8.
Qatar University
College of Engineering
Numerical Methods – GENG 300
t=0, y=y0
Example 1
dy
4 e 0 .8 t 0 . 5 y
dt
Solve above ode from t=0 to 4 using ODE solvers in MATLAB. Analytical solution to this ODE
4 0.8t 0.5t
y (e e ) 2e0.5t
1.3
MATLAB code
Define function
function dy = program1(t,y)
dy = 4*exp(0.8*t)-0.5*y
[t,y] = solver(@function,tspan,y0)
[t,y] = solver(@program1,tspan,y0)
h = (b - a)/m;
T = zeros(1,m+1);
Y = zeros(1,m+1);
T(1) = a;
Y(1) = ya;
for j=1:m,
Y(j+1) = Y(j) + h*feval(f,T(j),Y(j));
T(j+1) = a + h*j;
end
Qatar University
College of Engineering
Numerical Methods – GENG 300
Solution:
Comment: As we increase number of step size (smaller h), numerical solutions are closer
to analytical one.
Qatar University
College of Engineering
Numerical Methods – GENG 300
An example of a nonstiff system is the system of equations describing the motion of a rigid body
without external forces.
function dy = rigid(t,y)
dy = [y(2)*y(3); -y(1)*y(3);-0.51*y(1)*y(2)];
In this example we change the error tolerances using the odeset command and solve on a time
interval [0 12] with an initial condition vector [0 1 1] at time 0.
Plotting the columns of the returned array Y versus T shows the solution
plot(t,y(:,1),'-',t,y(:,2),'-.',t,y:,3),'.')
Qatar University
College of Engineering
Numerical Methods – GENG 300
Example 4
Example 5. Solving initial value 2nd order or higher order equation problems
1st step: Convert the 2nd order ODE into a pair of first-order ODEs by defining
dy1
y2
dt
dt
________________________________________________________________
-1
-2
-3
0 2 4 6 8 10 12 14 16 18 20
Qatar University
College of Engineering
Numerical Methods – GENG 300
Stiffness
A stiff system is one involving rapidly changing component along with the slowly
changing ones.
An example of a stiff system is provided by the van der Pol equations in relaxation oscillation.
The limit cycle has portions where the solution components change slowly and the problem is
quite stiff, alternating with regions of very sharp change where it is not stiff.
function dy = vdp1000(t,y)
dy = zeros(2,1); % a column vector
dy(1) = y(2);
dy(2) = 1000*(1 - y(1)^2)*y(2) - y(1);
For this problem, we will use the default relative and absolute tolerances (1e-3 and 1e-6,
respectively) and solve on a time interval of [0 3000] with initial condition vector [2 0] at time
0.
Plotting the first column of the returned matrix Y versus T shows the solution
plot(T,Y(:,1),'-o')
Qatar University
College of Engineering
Numerical Methods – GENG 300
Algorithms
ode45 is based on an explicit Runge-Kutta (4,5) formula, the Dormand-Prince pair. It is a one-
step solver – in computing y(tn), it needs only the solution at the immediately preceding time
point, y(tn-1). In general, ode45 is the best function to apply as a first try for most problems.
The above algorithms are intended to solve nonstiff systems. If they appear to be unduly slow,
try using one of the stiff solvers below.
ode15s is a variable order solver based on the numerical differentiation formulas (NDFs).
Optionally, it uses the backward differentiation formulas (BDFs, also known as Gear's method)
that are usually less efficient. Like ode113, ode15s is a multistep solver. Try ode15s when
ode45 fails, or is very inefficient, and you suspect that the problem is stiff, or when solving a
differential-algebraic problem.
Qatar University
College of Engineering
Numerical Methods – GENG 300
ode23t is an implementation of the trapezoidal rule using a "free" interpolant. Use this solver if
the problem is only moderately stiff and you need a solution without numerical damping. ode23t
can solve DAEs.