Final MA 240 Lab Manual
Final MA 240 Lab Manual
Lab Manual
MA 240
Numerical Methods
Prepared by
Dr. Arshi Khalid
In this lab the students will be using MATLAB application software run on a PC with
Windows operating system. Matlab 9.1 or later version are recommended for student
use.
Activity Weightage
MCQ Quizes 20%
Programming QUIZ Mid Term 30%
Programming QUIZ Final Term 30%
Lab Assignments/programming toy problems 20%
Introduction
This lab is an integral part of the course MA 240 NumericalMethods. The main objectives
of the lab are to experience using MATLAB to apply the numerical methods taught in the
class.
MATLAB R2007a is the software that will be used. In the following steps we will describes how to install
® ®
and activate MathWorks™ products on a computer running the Microsoft Windows operating system
(32-bit or 64-bit).
Insert the DVD into the DVD drive connected to your system or double-click the installer file you
downloaded from the MathWorks Web site. The installer should start automatically.
If you do not have an Internet connection, select the Install without using the Internet option and click
Next.
Review the software license agreement and, if you agree with the terms, select Yes and click Next.
After the installation is complete, you can view or print the license agreement using the file license.txt
located in the top-level installation folder.
If you do not have an Internet connection, and choose to install manually, the installer displays the File
Installation Key dialog box. A File Installation Key identifies the products you can install.
If you have the key, select the I have the File Installation Key for my license option, enter the File
Installation Key, and click Next. The administrator contact on a license can retrieve the File Installation Key
from the License Center at the MathWorks Web site.
If you do not have the key, select the I do not have the File Installation Key option and click Next. The
installer will provide you with the information you need to get a key.
If you choose the I do not have the File Installation Key option, the installer displays the Installation and
Activation Next Steps dialog box. This dialog box contains the information you need to retrieve your File
Installation Key from the License Center at the MathWorks Web site, including:
Host ID
Release number (e.g., R2010a)
Operating system user name (Note that user names are case-sensitive in activation.)
Save the information displayed in this dialog box. For example, you can print a copy by clicking Print. Take
the information to a computer with an Internet connection and visit the License Center at the MathWorks
Web site. The MathWorks uses this information to generate a File Installation Key and a License File. You
must have this information with you when you return to the computer on which you want to install and
activate the software. To exit the activation process, click Finish.
MA 240 NumericalMethods P a g e | 10
Step 4: Choose the Installation Type
In the Installation Type dialog box, specify whether you want to perform a Typical or Custom installation
and click Next.
Choose Typical if you have an Individual or Group license and do not need to specify which
products you want to install and do not need to access any installation options.
Choose Custom if you need to specify which products to install, need access to installation
options, or need to install the license manager (network license options only).
MA 240 NumericalMethods P a g e | 11
Step 5: Specify the Installation Folder
Specify the name of the folder where you want to install MathWorks products. You can accept the default
installation folder or specify the name of a different installation folder. If the folder doesn't exist, the installer
creates it.
When specifying a folder name, do not specify a name that contains the @ sign, an exclamation point (!),
the percent character (%), the plus sign (+), or the dollar sign character ($). The full path of the installation
folder must not include a folder named private. If you make a mistake while entering a folder name and
want to start over using the default folder name, click Restore Default Folder. To continue with the
installation, click Next.
MA 240 NumericalMethods P a g e | 12
Step 6: Specify Products to Install (Custom Only)
If you are performing a custom installation, you can specify which products you want to install in the
Product Selection dialog box. This dialog box lists all the products associated with the license you selected
or with the Activation Key you specified. In the dialog box, all the products are preselected for installation.
If you do not want to install a particular product, clear the check box next to its name.
After selecting the products you want to install, click Next to continue with the installation.
MA 240 NumericalMethods P a g e | 13
Step 7: Specify Installation Options (Custom Only)
For Custom installations, you can specify several installation options, including:
MA 240 NumericalMethods P a g e | 14
The following table provides brief descriptions of these file extensions.
.m MATLAB Code
.p MATLAB P-code
MA 240 NumericalMethods P a g e | 15
Step 8: Confirm Your Choices and Begin Copying Files
Before it begins copying files to your hard disk, the installer displays a summary of your installation
choices. To change a setting, click Back. To proceed with the installation, click Install.
As it copies files to your hard drive, the installer displays a status dialog box to show the progress of the
installation.
When the installation successfully completes, the installer displays the Installation Complete dialog box. In
this dialog box, you can choose to activate the software you just installed. You cannot use the software you
installed until you activate it. The MathWorks recommends activating immediately after installation. If you
logged in to your MathWorks Account during installation, your log-in session continues into the activation
process. Click Next to proceed with activation.
If you choose to exit the installer without performing activation, clear the Activate MATLAB option and
click Finish (the button label changes). You can activate later using the activation application.
MA 240 NumericalMethods P a g e | 16
Step 10: Activate Your Installation
Because you were not logged in to your MathWorks Account during installation, or you started the
activation application independently, you must choose whether to activate automatically or manually.
Select the Activate manually without the Internet option and click Next.
MA 240 NumericalMethods P a g e | 17
Step 11: Specify the Path to the License File
To activate without an Internet connection, you must have a License File. The License File identifies which
products you can run. The administrator contact on the license can retrieve the License File from the
License Center at the MathWorks Web site.
Select the Enter the path to the License File option and enter the full path of your License File in the text
box (or drag and drop the file) and click Next. If you do not have your License File, select the I do not
have a license file option.
MA 240 NumericalMethods P a g e | 18
If You Do Not Have a License File
If you are activating manually and do not have your License File, the License File Retrieval dialog box explains
how to get your License File and finish activation. The dialog box displays the information you will need to get
your License File, including:
Host ID
Operating system user name (Note that user names are case-sensitive in activation.)
Save the information displayed in this dialog box. For example, you can print a copy by clicking Print. Take
the information to a computer with an Internet connection and visit the License Center at the MathWorks Web
site. The MathWorks uses this information to generate a File Installation Key and a License File. You must
have this information with you when you return to the computer on which you want to install and activate the
software. To exit the activation application, click Finish.
Note Your installation will not be activated. You cannot run MATLAB until you retrieve your License File.
MA 240 NumericalMethods P a g e | 19
Step 12: Complete the Activation
After activating your installation, you can run The MathWorks software. If you do not want to run MATLAB
now, clear the Start MATLAB option and click Finish to exit the activation process.
MA 240 NumericalMethods P a g e | 20
Reference: The Math Works - http://www.mathworks.com
MA 240 NumericalMethods P a g e | 21
Laboratory #1 – Introduction to MATLAB
1. Laboratory Objective
Getting Started
On your Windows desktop, double-click the MATLAB shortcut icon to start
MATLAB program.
To end your MATLAB session, select Exit MATLAB from the File menu or type quit
or exit in the Command Window.
MA 240 NumericalMethods P a g e | 22
Command Window
Used to enter the statements (Commands) and get the output
The prompt (>>) indicates MATLAB is ready to accept commands from you
MATLAB As a Calculator
The basic arithmetic operators are + - * / ^
Variables
An ―equals‖ sign is used to make an assignment
MATLAB does not require any type declarations or dimension statements.
Variable names consist of a letter, followed by any number of letters, digits, or
underscores.
MATLAB is a case sensitive.
The default variable is ―ans‖
Semicolon
in MATLAB the semicolon serves to suppress the output of the line that it
concludes.
If a statement is not terminated with a semicolon, then the result of the
statement is displayed.
MA 240 NumericalMethods P a g e | 23
Some useful command
Vector
Method 3: using the linspace function generates row vectors with equally spaced
elements
Syntax: linspace(firstValue,lastValue,numValues)
>> evens = linspace(0,10,6)
>> v = linspace(1,2,5)
Vector Operation
MA 240 NumericalMethods P a g e | 24
>> n = length(v)
Creates a matrix with specified values on a
diagonal >> diag(x)
Examples:
>> x = 2
>> y = x+3
>> 1+5
>> z = ans + 4
>> a = 2
>> b = 4;
>> b
Write a MATLAB command for the following operations:
56
3
2 * 2 43
4 *8
2
Write the MATLAB command(s) to
MA 240 NumericalMethods P a g e | 25
5. Laboratory Exercises
pi
43 0.123 * 5
Ex2: Let x = [3 2 6 8]' and y = [4 1 3 5]' (Note: x and y should be column vectors).
who : ………………………………………………………………………..
clc : ………………………………………………………………………..
MA 240 NumericalMethods P a g e | 26
Laboratory #2 –Introduction to Script Files and Matrices
1. Laboratory Objective
The objective of this laboratory is to show the use of scripts files and matrices in
MATLAB.
Format
Example:
>>format short
Scaled fixed point format, with 4 digits after the decimal point. For
example, 3.1416.
>>format long
Scaled fixed point format with 14 to 15 digits after the decimal point. For example,
3.141592653589793.
>>format rat
MA 240 NumericalMethods P a g e | 27
Mathematical MATLAB Functions
cos(x) Cosine of x
sin(x) Sine of x
tan(x) Tangent of x
sqrt(x) Square root of x
abs(x) Absolute value of x
exp(x) Exponential of x
log(x) Log to the base e of x
Example:
>>cos(pi)
ans =
-1
>> sin(pi/2)+cos((3*pi)/2)
ans =
1.0000
>>sqrt(25)
ans =
5
Scripts
MA 240 NumericalMethods P a g e | 28
Example
Matrices
A matrix generally refers to a 2-dimensional array, i.e. an m×n array where m and n
are greater than 1
MATLAB allow you to build matrices of your own with any entries that you may
want
You only have to follow a few basic conventions:
Separate the elements of a row with blanks or commas.
Use a semicolon ‗ ; ‗ to indicate the end of each row.
Surround the entire list of elements with square brackets, [ ].
Special Matrices
MA 240 NumericalMethods P a g e | 29
You can also look at specific parts of a matrix
>> A(1:3,:)
>> A(:,1) % whole column
>> A(1,:) % whole row
Matrix Operations
>>A+B
>>A*B
Matrix Functions
a. Multibly A by b
b. Add 4 to vector a
c. Multibly a by b
d. Multiply A by the inverse a
e. Find the square of A
f. Raise A to the power of 2
g. Find rows 2 and 3 in matrix A.
MA 240 NumericalMethods P a g e | 30
2 4 1
Given the matrix A 6 7 2 Provide the command needed to
3 5 9
a. Assign the first row of A to a vector called x
b. Assign the last 2 columns of A to a matrix called y
c. Add 6 to each element of A
d. Find the sum of all elements in x
e. Find the square of all elements in y
f. Save all commands in a script file mat.m and run the script
from command window.
5. Laboratory Exercises
Ex1: Write a MATLAB command for the following operations and format the output to
be short:
6
sin( ) 7
3 2*5
3
sqrt(9) 4 0.123* cos( )
1 0 2 2 0 16
Ex2: Let A 3 9 7 and B 8 6 1 Find the following:
2 4 1 20 4 4
1. A transpose
2. A+B
3. Multibly A by 0.5
4. Devide B by 2
5. Find the square of A
6. Raise B to the power of -1
EX3: Use rand function to create a 9x8 matrix. Then answer the following:
a. Make a matrix that is the transpose of the original matrix
b. Assign the row 8 of the original matrix to a vector called b
c. Assign the columns 1 and 2 of the original matrix to a matrix called c
d. Write all commands in a sript file name it EX3.m and run it from command
window.
MA 240 NumericalMethods P a g e | 31
Laboratory #3 – Functions in MATLAB
1. Laboratory Objective
Graphics: Plot
Multiple x-y pairs create multiple graphs with a single call to plot.
>> x = 0:pi/30:2*pi;
>> y = sin(3*x);
>> y2= sin(3*x-0.2);
>> y3= sin(2*x);
>> plot(x,y,x,y2,x,y3)
MA 240 NumericalMethods P a g e | 32
Function
Functions are m-files that takes certain inputs and return certain outputs p. The
first line of a function must be of the form
function [outputs]=functionname(inputs)
where:
outputs stands for any outputs that the function should return.
Inputs stands for any variable or values that need to be used as inputs
for the m-file.
Inputs and outputs are comma-separated lists of variable names
The name of the M-file and of the function should be the same
The name of an M-file begins with an alphabetic character and has a
filename extension of .m.
Example 1
function y=f1(x)
y=2*x.^3-3*x+1;
Example 2
function [s,p] = addmult(x,y) %This is addmult.m Compute sum and
%product of two matrices
s=x+y;
p=x*y;
Example 1
MA 240 NumericalMethods P a g e | 33
Example 2
How to call the addmult if the inputs :
1. 2, 4
2. [1 2; 3 4] , [2 2; 1 1]
3. [1 2 3]; [1 0 1]
In this laboratory you are required to plot the following function for -2 ≤ x ≤ 2 using
100 equally spaced points.
x2 0x1
x1
f e x1
0 otherwise
Write a MATLAB function that find the absolute value of any input number x.
2
Write MATLAB function to solve the equation ax + bx + c = 0. The output should
be the two roots, and the input shall be a, b, c
2
x b b 4ac
1
2a
2
x
b b 4ac
22a
MA 240 NumericalMethods P a g e | 34
5. Laboratory Exercises
2
Ex2: Giving that f (x) x 1 plot the function in [-4,4]
Ex3: Write a MATLAB function SurfaceA to compute the surface area of sphere with
radius r where :
2
Surface Area = 4 π r
>>SurfaceA(3)
ans =
113.0973
Ex4: Write a MATLAB function probA which take the value of x and y as inputs
and calculate the a and b according to the following formula
a 2 x 2 y
b cos(x) sin( y)
MA 240 NumericalMethods P a g e | 35
Laboratory #4 – If Statement and For loop
1. Laboratory Objective
The objective of this laboratory is to introduce input command, IF Statement and For
loop in MATLAB.
Syntax
evalResponse = input(prompt)
strResponse = input(prompt, 's')
evalResponse = input(prompt)
Displays the prompt string on the screen, waits for input from the keyboard,
evaluates any expressions in the input, and returns the value in
evalResponse. To evaluate expressions, the input function accesses variables
in the current workspace.
strResponse = input(prompt, 's')
Example
Write a MATLAB command to read a vector X
X=
1 2 3
MA 240 NumericalMethods P a g e | 36
Relational Operators
Logical Operator
MA 240 NumericalMethods P a g e | 37
If Statement
Syntax:
if statement, condition.
if expression
statements
elseif expression
tatements
else
statements
End
Example1
Example2
function b=even(n)
% b=even(n). If n is an even
% integer, then b=1 otherwise,
% b=0.
if (mod(n,2)==0)
b=1;
else
b=0;
end
MA 240 NumericalMethods P a g e | 38
For Loops
Syntax:
for variable = 1:n,
statement,
...,
end
Example 1
function S=mySum(a)
N=length(a)
S=0
for i=1:N,
S=S+a(i)
end
k = 10;
hilbert = zeros(k,k); % Preallocate matrix
for m = 1:k
for n = 1:k
hilbert(m,n) = 1/(m+n -1);
end
end
MA 240 NumericalMethods P a g e | 39
4. Laboratory Problem Description
In this laboratory you are required to trace the following scripts and write the output:
% If Statement
bal = input('type balance:
') if (bal < 5000)
rate = 0.03
elseif (bal < 10000)
rate = 0.0325
else
rate = 0.035
end
b 2
i, j i j 1
MA 240 NumericalMethods P a g e | 40
5. Laboratory Exercises
Ex1: Write a MATLAB function to input an integer n and build the n by n matrix
ij
A with entries aij = 2
Ex2: Write a MATLAB function Grad that takes student MT1 ,MT2 out of 25 and Final
out of 50 as input and calculate Total out of 100 and return the Grade as output
according to the following scale:
> = 90 A
> = 80 B
> = 70 C
> = 60 D
Else F
>>grad(22,23,45)
Total =
90
Grade =
Ex3: Write a MATLAB function fact that read N as input from user and compute N!
(Hint : N! = 1X2X….XN)
MA 240 NumericalMethods P a g e | 41
Laboratory #5 – Solving Linear Systems in MATLAB
1. Laboratory Objective
sym
Symbolic numbers, variables, and objects
Syntax
S = sym(A)
x = sym('x')
x = sym('x', 'real')
Description
S = sym(A) constructs an object S, of class 'sym', from A. If the input argument
is a string, the result is a symbolic number or variable. If the input argument is a
numeric scalar or matrix, the result is a symbolic representation of the given
numeric values.
x = sym('x') creates the symbolic variable with name 'x' and stores the result in
x. x = sym('x', 'real') also assumes that x is real
x – 2y + z=0
2y – 8z = 8
-4x + 5y + 9z = -9
MA 240 NumericalMethods P a g e | 42
We can solve this system in several ways in MATLAB; you will learn two of
them in this part and another in the next part.
First we need to save the coefficients of the system in a matrix, and the right-hand
side vector in another matrix. Enter
A = [1 -2 1
0 2 -8
-4 5 9]
b = [0; 8; -9]
The three numbers you see are the solution values of x, y, and z.
Example:
>> A=[4 -1 1;2 5 2;1 2 4]
>> b=[8 3 11]'
>> x=A\b
You can easily check whether the solution is correct. The matrix product A times
X should equal the right hand side b. Does it? Check it out.
If you have MATLAB's Symbolic Math Toolkit, you can also use the "solve"
command to solve the above system. Enter
syms x y z
eq1 = 'x - 2*y + z = 0';
eq2 = '2*y - 8*z = 8';
eq3 = '-4*x + 5*y + 9*z = -9';
[x,y,z] = solve(eq1, eq2, eq3)
When you have a system with fewer equations than unknowns, you can find the
symbolic solution for some of the variables in terms of others, which we could call
"free" variables. Consider the following system of three equations in four unknowns.
x – 2y + z + 2w = 0
2y – 8z + w = 8
-4x + 5y + 9z - w = -9
MA 240 NumericalMethods P a g e | 43
We can solve for x, y, and z in terms of w. The last entry in the "solve" command
tells which variables are to be solved for, and hence which variable will be free. Enter
syms x y z w
eq1 = 'x - 2*y + z + 2* w = 0';
eq2 = '2*y - 8*z + w = 8';
eq3 = '-4*x + 5*y + 9*z - w = -9';
[x,y,z] = solve(eq1, eq2, eq3, 'x,y,z')
Syntax
seidel(A,b,x0,tol,itmax)
Example
Syntax
>>n=norm(A)
>>n = norm(A,p)
Description
The norm of a matrix is a scalar that gives some measure of the magnitude
of the elements of the matrix. The norm function calculates several different
types of matrix norms:
n = norm(A) returns the largest singular value of A, max(svd(A)).
n = norm(A,p) returns a different kind of norm, depending on the value of p.
MA 240 NumericalMethods P a g e | 44
Example1:
x = [0 1 2 3]
x=
0 1 2 3
norm(x)
ans =
3.7417
Example2:
LU Factorization
lu - LU matrix factorization
Syntax
>>Y = lu(A)
>>[L,U] = lu(A)
>>[L,U,P] = lu(A)
Description
returns unit lower triangular matrix L, uppertriangular matrix U,
and permutation matrix P so that P*A = L*U INPUTS: A: nxn
matrix
MA 240 NumericalMethods P a g e | 45
Example1:
Let A = [ 1 2 3
4 5 6
7 8 0 ];
L1 =
0.1429 1.0000 0
0.5714 0.5000 1.0000
1.0000 0 0
U=
7.0000 8.0000 0
0 0.8571 3.0000
0 0 4.5000
Using three arguments on the left side to get the permutation matrix as
well,
>>[L2,U,P] = lu(A)
returns a truly lower triangular L2, the same value of U, and the
permutation matrix P.
L2 =
1.0000 0 0
0.1429 1.0000 0
0.5714 0.5000 1.0000
U=
7.0000 8.0000 0
0 0.8571 3.0000
0 0 4.5000
P=
0 0 1
1 0 0
0 1 0
MA 240 NumericalMethods P a g e | 46
4. Laboratory Problem Description
In this laboratory you are required to Find the solution of the following systems of
linear equation:
1) x1 + x2 + x3 = 3
4x1 - x2 - x3= 2
x1 + 2x2 - x3= 2
2)
5. Laboratory Exercises
x + 4y + 3z = 10
2x + y – z = -1
3x – y – 4z = 11
5 x1 + x2 + x3 +2x4 = 8
2 x1 +4 x2 – x4 = -3
x1 + 3x3 = 7
2 x1 – x2 +3 x3 +8x4 = 17
MA 240 NumericalMethods P a g e | 47
Laboratory #6 – Polynomials
1. Laboratory Objective
To enter this into MATLAB, just enter it as a vector in the following manner
>>x = [1 3 -15 -2 9]
x=
1 3 -15 -2 9
MATLAB can interpret a vector of length n+1 as an nth order polynomial. Thus, if your
polynomial is missing any coefficients, you must enter zeros in the appropriate place
in the vector. For example,
y = [1 0 0 0 1]
You can also extract the roots of a polynomial. This is useful when you have a high-
order polynomial such as
MA 240 NumericalMethods P a g e | 48
Finding the roots would be as easy as entering the following command;
ans =
-5.5745
2.5836
-0.7951
0.7860
Syntax
>>p = poly(A)
>>p = poly(r)
Description
p = poly(A) where A is an n-by-n matrix returns an n+1 element row vector whose
elements are the coefficients of the characteristic polynomial, . The
coefficients are ordered in descending powers: if a vector c has n+1 components,
the polynomial it represents is
p = poly(r) where r is a vector returns a row vector whose elements are the
coefficients of the polynomial whose roots are the elements of r.
Remarks
Note the relationship of this command to
r = roots(p)
which returns a column vector whose elements are the roots of the polynomial
specified by the coefficients row vector p. For vectors, roots and poly are inverse
functions of each other, up to ordering, scaling, and roundoff error.
Example1
MATLAB displays polynomials as row vectors containing the coefficients
ordered by descending powers. The characteristic equation of the matrix
A=
1 2 3
4 5 6
7 8 0
is returned in a row vector by poly:
p = poly(A)
p=
1 -6 -72 -27
MA 240 NumericalMethods P a g e | 49
The roots of this polynomial are returned in a column vector by roots:
r = roots(p)
r=
12.1229
-5.7345
-0.3884
Polynomial derivative
Syntax
k = polyder(p)
k = polyder(a,b)
[q,d] = polyder(b,a)
Description
Example1
The derivative of the
product is obtained with
>>a = [3 6 9];
>>b = [1 2 0];
>>k = polyder(a,b)
k=
12 36 42 18
This result represents the polynomial
MA 240 NumericalMethods P a g e | 50
Polynomial Evaluation
Syntax
>>y = polyval(p,x)
Description
y = polyval(p,x) returns the value of a polynomial of degree n evaluated at
x. The input argument p is a vector of length n+1 whose elements are the
coefficients in descending powers of the polynomial to be evaluated.
>>p = [3 2 1];
>>polyval(p,[5 7 9])
ans =
86 162 262
MA 240 NumericalMethods P a g e | 51
4. Laboratory Problem Description
In this laboratory you are required to find the value of the following polynomials:
at s=2,
4 3 2
y = x + 2 x – 7 x – 8 x + 12
Compute the derivative for the following polynomials:
f(x)=
3
f (x) x 2x 1
5. Laboratory Exercises
MA 240 NumericalMethods P a g e | 52
Laboratory #7 – Eigenvalues and Eigenvectors
1. Laboratory Objective
Syntax
d = eig(A)
d = eig(A,B)
[V,D] = eig(A)
Description
d = eig(A) returns a vector of the eigenvalues of matrix A.
d = eig(A,B) returns a vector containing the generalized eigenvalues, if A and B
are square matrices.
[V,D] = eig(A) produces matrices of eigenvalues (D) and eigenvectors (V) of matrix
A, so that A*V = V*D. Matrix D is the canonical form of A — a diagonal matrix with
A's eigenvalues on the main diagonal. Matrix V is the modal matrix — its columns
are the eigenvectors of A.
Characteristic Equation
(1)
MA 240 NumericalMethods P a g e | 53
where is the identity matrix and is the determinant of the matrix . Writing out
explicitly gives
(2)
(3)
The solutions of the characteristic equation are called eigenvalues, and are
extremely important in the analysis of many problems in mathematics and physics.
The polynomial left-hand side of the characteristic equation is known as the
characteristic polynomial.
Example
Compute characteristic polynomial for :
>> A=[10 -7 0;-3 2 6;5 -1 5]
A=
10 -7 0
-3 2 6
5 -1 5
>> p = poly(A)
p=
MA 240 NumericalMethods P a g e | 54
4. Laboratory Problem Description
In this laboratory you are required to find eigenvalue and eigenvectors for A in the
following systems of linear equation Ax=B:
17x1+2x2+3x3+4x4 = 4
5x1+6x2+7x3+8x4 = 3
9x1+10x2+11x3+12x4 = 2
13x1+14x2+15x3+16x4 = 1
Verify that the columns of X in the example above indeed are eigenvectors to the
matrix A. In other words, multiply (using Matlab) the matrix A to the columns (one at
a time) of X and check that they are eigenvectors corresponding to the eigenvalues.
5. Laboratory Exercises
A 1 0 3
MA 240 NumericalMethods P a g e | 55
Laboratory #8 – Interpolation
1. Laboratory Objective
Syntax
>>p = polyfit(x,y,n)
Description
p = polyfit(x,y,n) finds the coefficients of a polynomial p(x) of degree n that fits the
data, p(x(i)) to y(i), in a least squares sense. The result p is a row vector of length
n+1 containing the polynomial coefficients in descending powers:
[p,S] = polyfit(x,y,n) returns the polynomial coefficients p and a structure S for use
with polyval to obtain error estimates or predictions.
Example:
1
Given f (x) x find the interpolating polynomial approximate the value of 1.5
x 2 4 5
f(x) 0.5 0.25 0.2
>> x=[2 4 5]
x=
2 4 5
MA 240 NumericalMethods P a g e | 56
>> p=polyfit(x,y,2)
p=
0.0250 -0.2750 0.9500
>> polyval(p,1.5)
ans =
0.5937
Syntax
>>lagrange(x,y,a)
Description
determines the coefficients of the Lagrange interpolating polynomial p(x)
and computes p(a)
INPUTS: The vectors x and y and the value a
Example:
Use lagrange.m function to find the Lagrange interpolating polynomial and
approximate the value of 1.5
x 0 1 2 3
y -5 -6 -1 16
>>x=[0 1 2 3]
>>y=[-5 -6 -1 16]
>>lagrange(x,y,1.5)
In this laboratory you are required to find the interpolating polynomial of the
following data.
z 1 2 3 4 4.5
w -1 0 3 3.5 2
MA 240 NumericalMethods P a g e | 57
5. Laboratory Exercises
EX1: Find the coefficients of the Lagrange interpolating polynomial that interpolates
the function f (x) x 2 at 25 equally spaced points in the interval [4,7].
Approximate the value of f(5.975)
EX2: Find the interpolating polynomial that interpolates the function f(x) =
sin(3+x) over the interval [0,π] using 5 equally spaces.
Approximate the values of f ( 3 ) and f( 2)
MA 240 NumericalMethods P a g e | 58
Laboratory #9 – Least Squares Regression
1. Laboratory Objective
Syntax
>> linlsqr(x,y)
Description
Constructs a least square line y = ax + b that best fits a table of x and y
values INPUTS: The ROW vectors x and y
MATLAB Code
function linlsqr(x,y)
% Construct a least square line y=ax+b
% that fits x and y row or column
vectors. n=length(x);
n=length(y);
sumx=sum(x);
sumy=sum(y);
sumx2=sum(x.*x)
;
sumxy=sum(x.*y)
;
a=(n*sumxy-sumx*sumy)/(n*sumx2-sumx^2);
b=(sumx2*sumy-sumxy*sumx)/(n*sumx2-sumx^2);
disp(' linear least squares')
fprintf('\n a =%12.6f\n',a)
fprintf(' b =%12.6f\n',b)
disp('_________________________________________________________')
disp(' x y a*x+b |y-(ax+b)| ')
disp('_________________________________________________________'
) for i=1:n
yl=a*x(i)+b;
err(i)=abs(yl-y(i));
fprintf('%6.2f %6.2f %12.6f %12.6f\n',x(i),y(i),yl,err(i))
end
err=sum(err.*err);
fprintf('\n E(a,b) =%12.6f\n',sum(err))
MA 240 NumericalMethods P a g e | 59
Example:
Constructs a least square line y = ax + b, that best fits the following values of
x and y
x 2 4 5
y 0.5 0.25 0.2
>> x=[2 4 5]
x=
2 4 5
>> linlsqr(x,y)
linear least squares
a = -0.103571
b = 0.696429
_________________________________________________________
x y a*x+b |y-(ax+b)|
_________________________________________________________
2.00 0.50 0.489286 0.010714
4.00 0.25 0.282143 0.032143
5.00 0.20 0.178571 0.021429
E(a,b) = 0.001607
x 0 -1 4 5 7
y 5 1 3 2 -1
>>x=[0 -1 4 5 7]
>>y=[5 1 3 2 -1]
>>polyfit(x,y,2)
MA 240 NumericalMethods P a g e | 60
linear regression
f x xxf
2
a1
N x (x)2
2
a2 N xf x f
N x (x)2
2
linearization line
Syntax
a2
G(x) = a1 x , where
f x xx f
2
a1
N x (x)2
2
a2 N x f x f
x
2
(x)2N
a
a1 e 1
MA 240 NumericalMethods P a g e | 61
4. Laboratory Problem Description
In this laboratory you are required to find the least square polynomial of degree 3
x 1 3 4 5 7
y 0 1 3 2 -1
>>x=[1 3 4 5 7]
>>y=[0 1 3 2 -1]
>>polyfit(x,y,3)
Write a MATLAB script to find the least square line that best fits the following data,
Apply linear regression, linearization, and nonlinear regression
x 5 7 6 4
y 8 9 4 1
(Hint: G(x) = a1 + a2 x)
x=[5 7 6 4]
y=[8 9 4 1]
disp=('linear regression')
N=length(x)
sumx=sum(x)
sumy=sum(y)
sumxy=sum(x.*y)
sumsqx=sum(x.^2)
a1=((sumy*sumsqx)-(sumx*sumxy))/(N*sumsqx-(sumx)^2)
a2=(N*sumxy-sumx*sumy)/(N*sumsqx-(sumx)^2)
G=a1+a2*x
MA 240 NumericalMethods P a g e | 62
Linearization Solution:
disp=('linearization')
xbar=log(x)
ybar=log(y)
sumybar=sum(ybar)
sumsqxbar=sum(xbar.^2)
sumxbar=sum(xbar)
sumxybar=sum(xbar.*ybar)
sqsumxbar=sum(xbar.^2)
a1bar=((sumybar*sumsqxbar)-(sumxbar*sumxybar))/(N*sumsqxbar-
(sumxbar).^2)
a1=exp(a1bar)
a2=(N*sumxybar-sumxbar*sumybar')/(N*sumsqxbar-(sumxbar).^2)
G=a1*x.^a2;
Nonlinear Solution:
disp=('nonlinear')
sumysqx=sum(y.*x.^2)
sumcueb=sum(x.^3)
sumfth=sum(x.^4)
A=[N sumx sumsqx; sumx sumsqx sumcueb; sumsqx sumcueb sumfth]
B=[sumy ; sumxy ; sumysqx]
Sol=A\B
a1=Sol(1)
a2=Sol(2)
a3=Sol(3)
G=a1+a2*x+a3*x.^2
MA 240 NumericalMethods P a g e | 63
5. Laboratory Exercises
EX1: Write a MATLAB script to find the least square line that best fits the following
data:
x 0 2 4 6 8 10 12 14 16
N x 2 (x)2 N x 2 (x)2
1 2
f x x x
a1 a N x f x f
2
N x ( x)
f
x x)
2 2 2 2 2
N (
a
a1 e 1
EX3: Find linearization line that best fits the following data
x 2 4 6 8 10 12 14 16
y 2 5 9 18 24 32 40 51
MA 240 NumericalMethods P a g e | 64
Laboratory #10 – Root Finding Methods
1. Laboratory Objective
Description
inline(expr) constructs an inline function object from the MATLAB
expression contained in the string expr.
Example:
>> g = inline('t^2')
g=
Inline function:
g(t) = t^2
Stopwatch timer
Syntax
>> tic
>> …..% any statments
>>toc
MA 240 NumericalMethods P a g e | 65
Description
tic starts a stopwatch timer.toc prints the elapsed time since tic was used.t
= toc returns the elapsed time in t.
Example:
>> tic
>> for n = 1:10
A = rand(n,n);
>> toc
Elapsed time is 58.451261 seconds.
Syntax
>>bisect(f,a,b,tol,n)
Description
Finds the solution of an equation using bisection method
INPUTS:
f: the f(x) function
a and b: endpoints
tol: a tolerance
n: The maximum number of iterations
Example
Use MATLAB function bisect.m to find the roots of the function
f(x) = x3-x2-1 in [1,2] where ε = 0.01
>> f= inline('x^3-x^2-1')
f=
Inline function:
f(x) = x^3-x^2-1
>> bisect(f,1,2,0.01,15)
_____________________________________________________
iter a b c f(c) |b-a|/2
_____________________________________________________
MA 240 NumericalMethods P a g e | 66
5 1.4375 1.4688 1.453125 -0.043194 0.015625
Syntax
>> secant(f,x0,x1,tol,n)
Description
Finds the solution of an equation using the secant method
INPUTS:
f: the f(x) function
x0 and x1: initials approximations
tol: a tolerance
n: The maximum number of iterations
Example
>> f= inline('x^6-x-1')
f=
Inline function:
f(x) = x^6-x-1
>> secant(f,1,1.5,0.05,15)
______________________________________________________________
iter xn f(xn) f(xn+1)-f(xn) |xn+1-xn|
______________________________________________________________
0 1.000000 -1.000000
0 1.500000 8.890625 9.890625 0.500000
1 1.050553 -0.706218 -9.596843 0.449447
2 1.083627 -0.464507 0.241711 0.033074
Syntax
>>newton(f,df,x0,tol,n)
Description
Finds the solution of an equation using the Newton method
INPUTS:
f: the f(x) function
df: the f '(x) function
x0: initials approximation
tol: a tolerance
n: The maximum number of iterations
MA 240 NumericalMethods P a g e | 67
Example
>> f= inline('x^6-x-1')
f=
Inline function:
f(x) = x^6-x-1
>> df=inline('6*x^5-1')
df =
Inline function:
df(x) = 6*x^5-1
>> newton(f,df,0.5,0.05,15)
______________________________________________
iter x f(x) df(x) |xn+1-xn|
______________________________________________
0 0.500000 -1.484375 -0.812500
1 -1.326923 5.785438 -25.681979 1.826923
2 -1.101651 1.889224 -10.735786 0.225272
3 -0.925676 0.554828 -5.078000 0.175974
4 -0.816415 0.112535 -3.176241 0.109261
5 -0.780985 0.007897 -2.743272 0.035430
In this laboratory you are required to find the roots of the following equations
f(x) = -2x4 +x2 +12
f(x) = sin(x)
f(x) = 3x3 –x2 +4
f(x) = x2 - cos (x)
5. Laboratory Exercises
EX1: Use MATLAB build-in function to compare the speeds between (bisection,
2- f (x) x 2 in [0,1]
MA 240 NumericalMethods P a g e | 68
Appendix A: Rules to follow by Computer Lab Users
The loud conversations / discussion that disturbing the other users is prohibited.
Audio CDs or applications with audio output may only be used with headphones with minimum
volume that it should not be disturb other users.
All cell phones are to be turned off or set to silent while in the lab. If you receive a phone call, you
should exit the lab before answering your cell phone.
Do not bring food or beverages inside the lab.
Any file saved on the computer hard drive will be deleted without notice. Students should save their
work onto an external storage device such as USB drive or CD.
Changing hardware and software configurations in the computer labs is prohibited. This includes
modifications of the settings, modification of system software, unplugging equipment, etc.
Open labs are reserved for academic use only. Use of lab computers for other purposes, such as
personal email, non-academic printing, instant messaging, playing games, and listening to music is not
permitted.
Please leave the computer bench ready for the next patron. Leave the monitor on the login screen, and
do not forget to take goods related to you. While leaving computer bench please push the chair inside
the computer bench.
Users are responsible for their own personal belongings and equipment. Do not leave anything in the
Computer Lab unattended for any length of time. The Computer Labs staffs are not responsible for lost
or stolen items.
Users are not allowed to clear paper jams in the printer by themselves.
Operate the lab equipments with care.
After using white-board the user must clean for other user.
MA 240 NumericalMethods P a g e | 69
Appendix B: Endorsement
MA 240 NumericalMethods P a g e | 70