Numerical Analysis MATLAB MANUAL
Numerical Analysis MATLAB MANUAL
1
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
LABORATORY MANUAL
EXPERIMENTS IN
NUMERICAL ANALYSIS
REVISED SEPTEMBER 2015
2
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENTS IN
NUMERICAL ANALYSIS
This book or parts, therefore, may not be reproduced in any form without permission of
author.
3
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
About the author
4
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
CONTENTS
1 Introduction to MATLAB 6
5 Programming in MATLAB 44
6 Introduction to Loops 52
10 Interpolation in MATLAB 78
5
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT NO 1: INTRODUCTION TO MATLAB
a) EQUIPMENT
MATLAB software installed on your PC.
b) THEORY
MATLAB stands for MATrix LABoratory because its basic data element is a matrix (array). It is
widely used for mathematical computation, modeling, simulations, visualization and graphics,
and algorithm development. The MATLAB has optional toolboxes that are specially designed to
solve specific problems. i.e toolboxes for signal processing, robotics and control systems.
Literature that has been written about MATLAB assumes that the reader has knowledge of
computer programming.
i. MATLAB WINDOWS
When the program starts, the MATLAB desktop window opens, the window contain four
smaller windows: the command window, the current folder Window, the Workspace Window
and the Command History Window known as default view of tool. The list of different windows
their purposes are given in Table 1-1.
Window Purpose
Command Window Main window, enters variable, runs programs.
Figure Window Contain Output from graphic command.
Editor Window Create s and debug script and Function files.
Help Window Provides help related to MATLAB tool.
Workspace Window Provides information about the variables that
are used.
Current Folder Window Shows the file in the current folder.
Command History Logs commands entered in the command
Window window.
Table 1-1: MATLAB windows
6
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
iii. NOTES FOR WORKING IN THE COMMAND WINDOW
a) To type a command the cursor must be placed next to the command prompt (>>).
b) After entering the command, the Enter key is pressed, the command is executed.
c) Several commands can be typed in same line by simply placing comma in between
them. When Enter key is pressed the commands are executed in order from left to right.
d) It is not possible to go back to a previous line that is displayed in command window,
make a correction and re-execute it.
e) A previously typed command can be recalld to the command promt with the up arrow
(↑) and the down arrow (↓) can be used to move down the list of previously typed
commands.
f) If a command is too long to fit in one line , it can be continued to the next line by typing
three periods ….(called an ellipsis) and pressing the Enter Key.
THE SEMICOLON ( ; ):
When a command is typed in command window and Enter key is pressed , the command is
executed and output can be seen in command window. If a semicolon is inserted at the end of
the command, the command will be executed but the output will not be displayed on screen.
TYPING ( % ) :
the left hand side of the operator can be include only one variable name and the right hand side
of the operator can be a number, a variable and a complete expression which can compute the
result and store in it. When Enter key is pressed the right hand value is stored in the left hand
side variable.
v. ORDER OF PRECEDENCE
MATLAB executes the calculations according to the order of precedence displayed below. The
higher precedence operations are executed before the lower. If two or more have same
precedence, the expression is executed from left to right.
8
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Function Description Example
sqrt ( x ) Square root. >>sqrt( 81 ) ans=9
nthroot (x,n) Real nth root of a real number x >>nthroot (80,5) ans= 2.4022
exp(x) Exponential >>exp(5) ans=148.4132
abs(x) Absolute value >>abs(-24) ans=24
log(x) Natural logarithm (ln) >>log(1000) ans=6.9078
log10(x) Base 10 logarithm >>log10(1000) ans=3.0000
factorial(x) X must be a positive number >>factorial(5) ans=120
sin(x) Sine of angle x in radians >>sin(pi/6) ans=0.5
sind(x) Sine of angle x in degrees
cos(x) cos of angle x in radians
cosd(x) cos of angle x in degrees >>cosd(30) ans=0.86
tan(x) tan of angle x in radians >>tan(pi/6) ans=0.5774
tand(x) tan of angle x in degrees
Table 1-2: Built-in Function of MATLAB
The inverse trigonometric functions are asin(x), acos(x), atan(x), acot(x) for the angle in radians;
asind(x), acosd(x), atand(x), for angles in degrees the hyperbolic trigonometric functions are
sinh(x), cosh(x), tanh(x) and coth(x).
9
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
vii. DEFINING A SCALAR VARIABLE
It is a name of a memory location, when a new variable is defined; MATLAB allocates an
appropriate memory space where the data is stored. When a variable is assigned a new value
the content of the location is replaced.
10
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
A different way of executing the commands is first to create a file with a list of commands, save
it and then run the file. The commands will be executed in order from top to bottom. If needed
command can be corrected or changed.
The command can also be typed in word and then copy paste in Editor. MATLAB automatically
number a new line when Enter key is pressed while writing command in Editor. A simple
program entered in Editor. The first few lines in editor are typically used for comments by
placing first character % in the start of it.
11
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Before a script file can be executed it has to be saved. This is done by choosing Save As… from
the file menu, selecting the location and entering the name of the file. While saving add the
extension .m . The rules for naming a script file are same as it is for naming a variable.
c) PROCEDURE
1. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the software.
3. Define the variable x as x= 2.34 and then evaluate the following expression in MATLAB.
Compute the results.
4. Define the variable t as t= 6.8 and then evaluate the following expression in MATLAB.
Compute the results.
12
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
5. Define the variable x and yas x=8.3 and y=2.4 and then calculate the following
expressions and compare the results.
6.
d) CONCLUSIONS
_____________________________________________________________________________________
_____________________________________________________________________________________
____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
13
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT NO 2: CREATING ARRAYS IN MATLAB
a) EQUIPMENT
MATLAB software installed on your PC.
b) THEORY
The array is a fundamental form that MATLAB uses to store and manipulate data. An array is a
list of numbers arranged in rows and/or columns. In science and engineering one-dimensional
arrays represents vectors and two-dimensional arrays often represents matrices.
Row Vector: To create a row vector type the elements with a space or a comma between the
Column Vector: To create a column vector type the left square bracket [ and then enter the
elements with a semicolon between them or press the Enter key after each element. Type the
right square bracket ] after the last element.
Creating a Vector with Constant Spacing: in the vector with constant spacing the difference
between the elements is the same i.e. in the vector v = 2 4 6 8 10, the spacing between the
elements is 2.
14
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
a. If the numbers m, q are such that the value of n that the value of n cannot be obtained
by adding q’s to m. then last element in the vector will be the last number that does not
exceed n.
b. If only two numbers (the first and the last) are typed ( the space is omitted), then the
default for the spacing is 1.
15
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Rows of a matrix can also be entered as vectors using the notation for creating vectors with
constant spacing or linspace command i.e.
16
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
v. THE TRANSPOSE OPERATOR
When transpose vector is applied to a vector, it switches the rows (column) vector to column
(row) vector. The transpose operator is applied by simply typing a single quote ‘ following the
variable to be transposed.
a. Vector: The address of an element in a vector is its position in row (column). For a
vector ve, ve(k) is the element of kth location.
b. Matrix: The address of the element is its position in matrix. For a matrix assigned to a
variable ma, ma(k,p)refers to element in k row and p column.
17
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
vii. USING A COLON : IN ADDRESSING ARRAYS
A colon can be used to address a range of elements in a vector or a matrix.
For a vector: v( : ) refers to all the elements of the vector. V(m:n) refers to elements m through
n of vector.
18
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
ix. ADDING ELEMENTS TO MATRIX
19
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
c) PROCEDURE
1. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the Software.
2. Create the following matrix H in MATLAB and solve the part (a) & (b). Note down the
commands to get the solution for all.
(a) Create a 2x4 matrix g such that its first
row includes the first two elements and
last two elements of the first row of H.
and the second row of G Includes the
second through the fifth elements of the third row of H.
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
(b) Create a 3x3 matrix G such that it’s first, second and third rows are the first, fourth
and sixth columns of matrix H.
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
3. Create the following matrix by using vector notation for creating vectors with constant
spacing and the linspace command. Do not type individual elements explicitly.
________________________________________________________________________
________________________________________________________________________
_______________________________________________________________________
4. Use the eye command to create the array A shown below. Then use the colon to
address elements in the arrays and the eye command to change A to match the array
shown on the right.
________________________________________________________________________
________________________________________________________________________
20
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
5. Create three row vectors in MATLAB and solve the following parts:
(a) Create a 3x3, matrix such that the first, second and third rows consist of the first three
elements of the vectors a, b and c. respectively.
(b) Use the three vectors in a MATLAB command to create a 3x3 matrix such that the first,
second and third columns consist of the last three elements of the vectors a, b and c
d) CONCLUSIONS
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
_________________________________________________________________________________
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
21
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT NO 3: MATHEMATICAL OPERATIONS WITH ARRAYS
a) EQUIPMENT
MATLAB software installed on your PC.
b) THEORY
The basic operation can be done in Matlab by two different ways. One way, it uses the
standard symbols and follows the rules of linear algebra. Second way, which is called
Element by Element operations.
22
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
ii. ARRAY MULTIPLICATION
1. The multiplication operation * is executed by MATLAB according to the rules of linear
algebra. This means that if A and B are two matrices, the operation A*B can be carried out
only if the number of columns in matrix A is equal to the number of rows in matrix B. The
result is a matrix that has the same number of rows as A and the same number of columns
as B.
2. The product of the multiplication of two square matrices (they must be of the same size)
is a square matrix of the same size. However, the multiplication of matrices is not
commutative. This means that if A and B are both n × n, then A*B ≠ B *A. Also, the power
operation can be executed only with a square matrix (since A*A can be carried out only if
the number of columns in the first matrix is equal to the number of rows in the second
matrix).
3. Two vectors can be multiplied only if they have the same number of elements, and one is
a row vector and the other is a column vector. The multiplication of a row vector by a
column vector gives a matrix, which is a scalar. This is the dot product of two vectors.
(MATLAB also has a built-in function, dot(a,b))
23
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
iii. ARRAY DIVISION
The division operation is also associated with the rules of linear algebra.
Identity matrix:
The identity matrix is a square matrix in which the diagonal elements are 1s, and the rest of
the elements are 0s. An identity matrix can be created in MATLAB with the eye command.
If a matrix A is square, it can be multiplied by the identity matrix, I, from the left or from the
right: AI = IA = A
Inverse of a matrix:
The matrix B is the inverse of the matrix A if, when the two matrices are multiplied, the
product is the identity matrix. Both matrices must be square and the multiplication order
can be BA or AB. BA = AB = I
The inverse of a matrix A is typically written as A–1. In MATLAB the inverse of a matrix can
be obtained either by raising A to the power of –1, or with the inv(A)function.
Not every matrix has an inverse. A matrix has an inverse only if it is square and its
determinant is not equal to zero.
Determinants:
A determinant is a function associated with square matrices. The determinant is a function
that associates with each square matrix A a number, called the determinant of the matrix.
The determinant is typically denoted by det(A) or |A|. The determinant is calculated
according to specific rules. For a second-order matrix the rule is:
The determinant of a square matrix can be calculated with the det command.
24
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Left division, \ : Left division is used to solve the matrix equation AX = B. So the solution of
AX = B is: X =A^–1 B
In MATLAB the last equation can be written by using the left division character. In the first,
MATLAB calculates A^–1 and then uses it to multiply B. In the second (left division), the
solution X is obtained numerically with a method that is based on Gauss elimination. The
left division method is recommended for solving a set of linear equations because the
calculation of the inverse may be less accurate than the Gauss elimination method when
large matrices are involved.
Right division, / :
The right division is used to solve the matrix equation XC = D. In this equation X and D are
row vectors. This equation can be solved by multiplying, on the right, both sides by the
inverse of C:
In MATLAB the matrix equation can be written using the right division character:
X = D/C
Example: Use matrix operations to solve the following system of linear equations.
4x – 2y + 6z = 8
2x + 8y + 2z = 4
6x + 10y + 3z = 0
the above system of equations can be written in the matrix form AX = B or in the form XC =
D:
25
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
iv. ELEMENT-BY-ELEMENT OPERATIONS
Addition and subtraction are by definition already element-by-element operations since
when two arrays are added (or subtracted) the operation is executed with the elements
that are in the same position in the arrays. Element-by-element operations can be done
only with arrays of the same size. Element-by-element multiplication, division, or
exponentiation of two vectors or matrices is entered in MATLAB by typing a period in front
of the arithmetic operator.
26
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Element-by-element calculations are very useful for calculating the value of a function at
many values of its argument. In the example below y = x^2 – 4x. Element-by-element
operation is needed when x is squared. Each element in the vector y is the value of y that is
obtained when the value of the corresponding element of the vector x is substituted in the
equation.
27
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
vi. BUILT-IN FUNCTIONS FOR ANALYZING ARRAYS
28
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
The rand command:
The rand command generates uniformly distributed random numbers with values between
0 and 1.
29
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
THE randi COMMAND
The randi command generates uniformly distributed random integer. The command can be
used to assign these numbers to a scalar, a vector, or a matrix.
c) PROCEDURE
1. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the Software.
2. Write down the commands to Solve the following system of five linear equations in
MATLAB
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
3. Using MATLAB, calculate the value of y for the following values of x using element-by-
element operations: 1,2,3,4,5,6,7.
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
30
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
4. Define the vector v= [2 4 6 8 10]. Then use the vector in a mathematical expression to
create the following vectors.
(a)______________________________________________________________________
(b)______________________________________________________________________
(c)______________________________________________________________________
(d)______________________________________________________________________
d) CONCLUSIONS
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
31
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT NO 4: TWO DIMENSIONAL PLOTS
a) EQUIPMENT
MATLAB software installed on your PC.
b) THEORY
Plots are a very useful tool for presenting information especially in engineering Plots can be
formatted to have a desired appearance using MATLAB. The line type (solid, dashed, etc.),
color, and thickness can be prescribed, line markers and grid lines can be added, as can titles
and text comments. Several graphs can be created in the same plot, and several plots can be
placed on the same page. Example plot is shown in figure-1 below.
Figure above contains two curves that show the variation of light intensity with distance.
32
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
The arguments x and y are each a vector (one-dimensional array). The two vectors must have
the same number of elements. When the plot command is executed, a figure is created in the
Figure Window. The vector that is typed first in the plot command is used for the horizontal
axis, and the vector that is typed second is used for the vertical axis.
Once the plot command is executed, the Figure Window opens and the plot is displayed
The plot appears on the screen in blue, which is the default line color. The plot command has
additional, optional arguments that can be used to specify the color and style of the line and
the color and type of markers, if any are desired. With these options the command has the
form:
Line specifiers are optional and can be used to define the style and color of the line and the
type of markers (if markers are desired). The line style specifiers are
33
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
The line color specifiers are:
plot(x,y) A blue solid line connects the points with no markers (default).
plot(x,y,‘r’) A red solid line connects the points.
plot(x,y,‘--y’) A yellow dashed line connects the points.
34
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
iii. PROPERTY NAME AND PROPERTY VALUE:
Properties are optional and can be used to specify the thickness of the line, the size of the
marker, and the colors of the marker’s edge line and fill. The Property Name is typed as a
string, followed by a comma and a value for the property, all inside the plot command.
To plot this data, the list of years is assigned to one vector (named yr), and the corresponding
sales data is assigned to a second vector (named sle).
35
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
iv. PLOT OF A FUNCTION
In many situations there is a need to plot a given function. This can be done in MATLAB by
using the plot or the fplot command. The use of the plot command is explained below.
Since the plot is made up of segments of straight lines that connect the points, to obtain an
accurate plot of a function, the spacing between the elements of the vector x must be
appropriate. Smaller spacing is needed for a function that changes rapidly.
36
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Figure 3: The Figure with a plot of the function
If the same function in the same domain is plotted with much larger spacing for example (0.3)
the plot that is obtained is shown in figure 4 above. The plot can be copied from the Figure
Window (in the Edit menu, select Copy Figure) and then pasted into other applications.
v. THE fplot COMMAND
The fplot command plots a function with the form y = f(x) between specified limits. The
command has the form:
1. Function
The function can be typed directly as a string inside the command. For example, if the function
that is being plotted is f(x) = 8x2 + 5cos(x) , it is typed as: ‘8*x^2+5*cos(x)’. The function to be
plotted can be typed as a function of any letter. For example, the function in the previous
paragraph can be typed as 8*z^2+5*cos(z)’ or ‘8*t^2+5*cos(t)’.
37
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
2. Limits:
The limits argument is a vector with two elements that specify the domain of x [xmin,xmax], or
a vector with four elements that specifies the domain of x and the limits of the y-axis
[xmin,xmax,ymin,ymax].
3. line specifiers:
The line specifiers are the same as in the plot command. For example, a plot of the function y =
x2 + 4sin(2x) for 1 –3 ≤ x ≤ 3 can be created with the fplot command by typing following
command and output plot window
Two or more graphs can be created in the same plot by typing pairs of vectors inside the plot
command. The command plot(x,y,u,v,t,h). The vectors of each pair must be of the same length.
MATLAB automatically plots the graphs in different colors so that they can be identified. It is
also possible to add line specifiers following each pair. For example the command plot(x,y,‘-
b’,u,v,‘--r’,t,h,‘g:’),Example is shown below
38
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Figure6: A plot of the function y = 3x3 – 26x + 10 and its first and second
vii. Using the hold on and hold off Commands
To plot several graphs using the hold on and hold off commands, one graph is plotted first with
the plot command. Then the hold on command is typed. This keeps the Figure Window with
the first plot open, including the axis properties and formatting if any was done. Additional
graphs can be added with plot commands that are typed next. Each plot command creates a
graph that is added to that figure. The hold off command stops this process. Using example of
derivatives,
39
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
viii. Using the line Command
With the line command additional graphs (lines) can be added to a plot that already exists. The
form of the line command is:
The major difference between the plot and line commands is that the plot command starts a
new plot every time it is executed, while the line command adds lines to a plot that already
exists. To make a plot that has several graphs, a plot command is typed first and then line
commands are typed for additional graphs. (If a line command is entered before a plot
command an error message is displayed). Using plot and line command in above mentioned
problem, we can create multiple graphs.
40
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
xi. The “title” command
The text command places the text in the figure such that the first character is positioned at the
point with the coordinates x, y. While g text command places the text at a position specified by
the user with mouse.
xiii. The “legend” command
The legend shows a sample of the line type of each graph that is plotted, and places a label.
The pos is an optional number that specifies where in the figure the legend is to be placed. The
options are:
pos = -1 Places the legend outside the axes boundaries on the right side.
pos = 0 Places the legend inside the axes boundaries in a location that interferes the least with
the graphs.
pos = 1 Places the legend at the upper-right corner of the plot (default).
pos = 2 Places the legend at the upper-left corner of the plot.
pos = 3 Places the legend at the lower-left corner of the plot.
pos = 4 Places the legend at the lower-right corner of the plot.
xiv. Formatting the text within the “xlabel, ylabel, title, text and legend” commands:
The formatting can be done either by adding modifiers inside the string, or by adding to the
command optional PropertyName and PropertyValue arguments following the string. The
modifiers are characters that are inserted within the string. Some of the modifiers that can be
added are:
41
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
A complete explanation of all the formatting features can be accessed in the Help Window
under Text and Text Properties. Exemplary syntax is shown below
An example of formatting a plot by using commands is given in the following script file.
42
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
c) PROCEDURE
1. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the Software.
2. Plot the given function in MATLAB and draw a graph on paper and compare the results
for following data:
4. Plot the figure below, which shows for , the graph of the function sin(x) and
graphs of the Taylor series expansion of sin(x) with one, two, and five terms. Label the
axes and display a legend.
d) CONCLUSIONS
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
43
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT NO 5: PROGRAMMING IN MATLAB
a) EQUIPMENT
MATLAB software installed on your PC.
b) THEORY
To change the flow of a program requires some kind of decision-making process within the
program. The computer must decide whether to execute the next command or to skip one or
more commands and continue at a different line in the program. The program makes these
decisions by comparing values of variables.
When the main program reaches the command line that has the user-defined function, it
provides input to the function and “waits” for the results. Defined function carries out the
calculations and transfers the results back to the main program, which then continues to the
next command
Solution:
The program in a script file is shown below. The program first calculates the pay by multiplying
the number of hours by the hourly wage. Then an if statement checks whether the number of
hours is greater than 40. If so, the next line is executed and the extra pay for the hours above
40 is added. If not, the program skips to the end.
44
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
ii. The if-else if-else-end Structure
This structure includes two conditional statements (if and elseif) that make it possible to
select one out of three groups of commands for execution. The first line is an if statement
with a conditional expression. If the conditional expression is true, the program executes group
1 of commands
45
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXAMPLE # 02 (WATER LEVEL IN WATER TOWER)
46
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
iii. THE switch-case STATEMENT
The switch-case statement is another method that can be used to direct the flow of a
program. It provides a means for choosing one group of commands for execution out of several
possible groups. The first line is the switch command, which has the form:
47
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXAMPLE # 03 (CONVERTING UNITS OF ENERGY)
Write a program in a script file that converts a quantity of energy (work) given in units of either
joule, ft-lb, cal, or eV to the equivalent quantity in different units specified by the user. The
program asks the user to enter the quantity of energy, its current units, and the desired new
units. The output is the quantity of energy in the new units.
48
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
49
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
c) PROCEDURE
1. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the Software.
2. Evaluate the following expression and write down the commands for each.
(a)______________________________________________________________________
(b)______________________________________________________________________
(c)______________________________________________________________________
(d)______________________________________________________________________
3.
(a)______________________________________________________________________
(b)______________________________________________________________________
(c)______________________________________________________________________
(d)______________________________________________________________________
4.
50
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
(a)_________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
(b)_________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
(c)_________________________________________________________________________
__________________________________________________________________________
5.
(a)______________________________________________________________________
(b)______________________________________________________________________
(c)______________________________________________________________________
(d)______________________________________________________________________
d) CONCLUSIONS
______________________________________________________________________________
______________________________________________________________________________
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
51
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIEMENT NO 6: INTRODUCTION TO LOOPS
a) EQUIPMENT
MATLAB software installed on your PC.
b) THEORY
Loop is another method to alter the flow of a computer program. In a loop, the execution of a
command, or a group of commands, is repeated several times consecutively. Each round of
execution is called a pass.
The loop index variable can have any variable name (usually i, j, k, m, and n are used,
however, i and j should not be used if MATLAB is used with complex numbers).
In the first pass k = f and the computer executes the commands between the for
and end commands. Then, the program goes back to the for command for the
second pass. k obtains a new value equal to k = f + s, and the commands between
the for and end commands are executed with the new value of k. The process
repeats itself until the last pass, where k = t. Then the program does not go back to
the for, but continues with the commands that follow the end command. For example,
if k = 1:2:9, there are five loops, and the corresponding values of k are 1, 3, 5, 7, and
9.
• The increment s can be negative (i.e.; k = 25:–5:10 produces four passes with k = 25,
20, 15, 10).
• If the increment value s is omitted, the value is 1 (default) (i.e.; k = 3:7 produces five
passes with k = 3, 4, 5, 6, 7).
• In the for command k can also be assigned a specific value (typed as a vector).
o Example: for k = [7 9 –1 3 3 5].
52
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXAMPLE # 1 (SUM OF A SERIES)
Solution
(a) A script file that calculates the sum of the first n terms of the series is shown below. The
summation is done with a loop. In each pass one term of the series is calculate for
53
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXAMPLE # 2: (CREATING A MATRIX WITH A LOOP)
Write a program in a script file that creates an matrix with elements that have the following
values. The value of each element in the first row is the number of the column. The value of
each element in the first column is the number of the row. The rest of the elements each has a
value equal to the sum of the element above it and the element to the left. When executed, the
program asks the user to enter values for n and m.
Solution
The program, shown below, has two loops (one nested) and a nested if else if-else-end
structure. The elements in the matrix are assigned values row by row. The loop index variable
of the first loop, k, is the address of the row, and the loop index variable of the second loop, h,
is the address of the column.
54
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
i. THE break AND continue COMMANDS
55
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
c) PROCEDURE
1. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the Software.
2.
3.
4.
5.
6.
56
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
d) CONCLUSION
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
____________________________________________________
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
57
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT # 7: USER DEFINED FUNCTIONS IN MATLAB
a) EQUIPMENT
MATLAB software installed on your PC.
b) THEORY
A user-defined function is a MATLAB program that is created by the user, saved as a function
file, and then can be used like a built-in function. The function can be a simple, single
mathematical expression or a complicated and involved series of calculations. The main feature
of a function file is that it has an input and an output. This means that the calculations in the
function file are carried out using the input data, and the results of the calculations are
transferred out of the function file by the output.
58
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
ii. STRUCTURE OF A FUNCTION FILE
The structure of a typical complete function file is shown in fig below. This particular function
calculates the monthly payment and the total payment of a loan. The inputs to the function are
the amount of the loan, the annual interest rate, and the duration of the loan (number of
years). The output from the function is the monthly payment and the total payment.
It is good practice to avoid names of built-in functions and names of variables already defined
by the user or predefined by MATLAB.
59
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
iv. FUNCTION BODY
The function body contains the computer program (code) that actually performs the
computations. The code can use all MATLAB programming features. This includes calculations,
assignments, any built-in or user-defined functions, flow control (conditional statements and
loops) as explained in LAB 6, comments, blank lines, and interactive input and output.
Several variables can be declared global by listing them, separated with spaces, in the
global command.
The global command has to be entered in the Command Window, or in a script file, for
the variable to be recognized in the workspace.
The variable can be assigned, or reassigned, a value in any of the locations in which it is
declared common.
A user-defined function is used in the same way as a built-in function. A function can be used by
assigning its output to a variable (or variables), as a part of a mathematical expression, as an
60
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
argument in another function, or just by typing its name in the Command Window or in a script
file. In all cases the user must know exactly what the input and output arguments are. An input
argument can be a number, a computable expression, or a variable that has an assigned value.
The arguments are assigned according to their position in the input and output argument lists
in the function definition line.
User-defined loan function in above Figure, which calculates the monthly and total payments
(two output arguments) of a loan. The input arguments are the loan amount, annual interest
rate, and the length (number of years) of the loan. In the first illustration the loan function is
used with numbers as input arguments:
61
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
62
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
c) PROCEDURE
1. Switch on your computer and double-click on the MATLAB icon on the
desktop to launch the Software.
2. Write a user-defined MATLAB function, with two input and two output
arguments, that determines the height in centimeters and mass in
kilograms of a person from his height in inches and weight in pounds. For
the function name and arguments use [cm,kg] = STtoSI(in,lb). The input
arguments are the height in inches and weight in pounds, and the output
arguments are the height in centimeters and mass in kilograms. Use the
function in the Command Window to:
(a) Determine in SI units the height and mass of a 5 ft 8 in. person who
weighs 175 lb.
(b) Determine your own height and weight in SI units.
63
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
argument y is the value. The function displays an error message if a
negative or non-integer number is entered when the function is called. Use
fact with the following numbers:
(a) 12! (b) 0! (c) –7! (d) 6.7!
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
64
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT 8: SOLVING NON-LINEAR EQUATIONS
a) EQUIPMENT
MATLAB software installed on your PC.
b) THEORY
Equations need to be solved in all areas of science and engineering. An equation of one variable
can be written in the form:
f(x) = 0
A solution to the equation (also called a root of the equation) is a numerical value of x that
satisfies the equation. Graphically, as shown in Fig. 9-1, the solution is the point where the
function f(x) crosses or touches the x-axis. An equation might have no solution or can have one
or several (possibly many) roots.
The bisection method is a bracketing method for finding a numerical solution of an equation of
the form f(x) = 0 when it is known that within a given interval [a, b], f(x) is continuous and the
65
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
equation has a solution. When this is the case, f(x) will have opposite signs at the endpoints of
the interval. As shown in Fig. 9-2, if f(x) is continuous and has a solution between the points x =
a and x = b , then either f(a) > 0 and f(b) < 0 or f(a) < 0 and f(b) > 0. In other words, if there is a
solution between x =a and x = b, then f(a)f(b) < 0.
1. Choose the first interval by finding points a and b such that a solution exists between
them. This means that f(a) and f(b) have different signs such that f(a)f(b) < 0. The points
can be determined by examining the plot of f(x) versus x.
2. Calculate the first estimate of the numerical solution xNS1 by:
xNS1 = (a+b)/2
3. Determine whether the true solution is between a and xNS1 or between xNS1 and b. This
is done by checking the sign of the product f(a) · f(xNS1) :
If f(a) · f(xNS1) < 0, the true solution is between a and xNS1
If f(a) · f(xNS1) > 0, the true solution is between xNS1 and b.
4. Select the subinterval that contains the true solution (a to xNS1, or xNS1 to b) as the new
interval [a, b], and go back to step 2.
66
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Steps 2 through 4 are repeated until a specified tolerance or error bound is attained.
Newton's method (also called the Newton-Raphson method) is a scheme for finding a
numerical solution of an equation of the form f(x) = 0 where f(x) is continuous and
differentiable and the equation is known to have a solution near a given point.
MATLAB has two built-in functions for solving equations with one variable. The fzero
command can be used to find a root of any equation, and the roots command can be used for
finding the roots of a polynomial.
The fzero command can be used to solve an equation (in the form f(x) = 0) with one variable.
The user needs to know approximately where the solution is, or if there are multiple solutions,
which one is desired. The form of the command is:
67
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
x is the solution, which is a scalar.
function is the function whose root is desired. It can be entered in three different
ways:
1. The simplest way is to enter the mathematical expression as a string.
2. The function is first written as a user-defined function, and then the function handle
is entered.
3. The function is written as an anonymous function, and then its name (which is the
name of the handle) is entered.
The function has to be written in a standard form.
An example is shown below.
The roots command can be used to find the roots of a polynomial. The form of the command is:
For further information on how to use this command, refer to MATLAB help.
c) PROCEDURE
1. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the software.
2. We want to find solution of the equation 8-4.5(x-sin(x))=0 using bisection method. First
plot the function using fplot command. Refer to MATLAB help for the syntax of the
command.
3. You will notice that solution of the equation lies between x=2 and x=3. Choosing these
as the lower and upper limit of the interval (a and b respectively) and a tolerance of
0.001 rad, implement the following program in a new script file. Let the maximum
number of iterations be 20.
68
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
4. Upon running the M-file generated by Step 3, you will get the following output. The
output shows that the solution with the desired tolerance was reached in the 10 th
iteration.
69
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
in the command if F(a)*FxNS < 0). Rewrite the program such that the anonymous
function F is used inside the loop only once. The input arguments are the same as in
step 3. Execute the new function from the command window using equation 8-4.5(x-
sin(x))=0 and check that the output is the same as in step 4.
6. Open a new script file and copy the following user-defined function of Newton’s method
in it and save it as NewtonRoot.m.
7. Use the function NewtonRoot created in step 7 to find the solution of the equation 8
- 4.5(x - sinx) = 0). In the command window, define 0.0001 for the maximum relative
error and 10 for the maximum number of iterations. Use x = 2 as the initial guess of the
solution. Note that your answer is approximately the same as the one obtained in step
5.
8. For the equation xe-x = 0.2, first plot the function using fplot command and then solve
by using fzero command. Execute commands from the command window.
Answer:
Using BisectionRoot:
Using built-in roots command:
10. *Determine the fourth root of 200 by finding the numerical solution of the equation x4 -
200 = 0. Use Newton's method. In the command window, set the initial value to 8; the
iterations should stop when the estimated relative error is smaller than 1 x 10-6. The
number of iterations should be limited to 20.
Note: Questions with asterisks (*) only to be done if rest of the steps are completed in time.
d) CONCLUSIONS
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
71
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT 9: POLYNOMIALS AND CURVE FITTING
a) EQUIPMENT
MATLAB software installed on your PC
b) THEORY
Curve fitting is a procedure in which a mathematical formula (equation) is used to best fit a
given set of data points. The objective is to find a function that fits the data points overall. It is
typically used when the values of the data points have some error. The procedure is also used
for determining the validity of proposed equations used to represent the data and for
determining the values of parameters (coefficients) in the equations. Curve fitting can be
carried out with many types of functions and with polynomials of various orders.
i. Curve Fitting with Polynomials
Polynomials can be used to fit data points in two ways. In one the polynomial passes through all
the data points, and in the other the polynomial does not necessarily pass through any of the
points, but overall gives a good approximation of the data. The two options are described
below.
ii. Polynomials that pass through all the points:
When n points (xi, yi) are given, it is possible to write a polynomial of degree n-1 that passes
through all the points. For example, if two points are given it is possible to write a linear
equation in the form y=mx+b that passes through the points. With three points the equation
has the form of y=ax2+bx+c. With n points the polynomial has the form an-1xn-1 + an-2xn-2 + ... +
a1x + a0. The coefficients of the polynomial are determined by substituting each point in the
polynomial and then solving the n equations for the coefficients.
iii. Polynomials that do not necessarily pass through any of the points:
When n points are given, it is possible to write a polynomial of degree less than n-1 that does
not necessarily pass through any of the points, but overall approximates the data. The most
common method of finding the best fit to data points is the method of least squares. In this
method the coefficients of the polynomial are determined by minimizing the sum of the
squares of the residuals at all the data points. The residual at each point is defined as the
difference between the value of the polynomial and the value of the data. For example,
consider the case of finding the equation of a straight line that best fits four data points as
shown in Figure 10-1.
Curve fitting with polynomials is done in MATLAB with the polyfit function, which uses the
least squares method. The basic form of the polyfit function is:
For the same set of m points, the polyfit function can be used to fit polynomials of any
order up to m-1. If n = 1 the polynomial is a straight line, if n = 2 the polynomial is a parabola,
and so on. The polynomial passes through all the points if n=m-1 (the order of the polynomial is
one less than the number of points). It should be pointed out here that a polynomial that
passes through all the points, or polynomials with higher order, do not necessarily give a better
fit overall.
Given a set of data points x and y where x is the independent variable and y is the dependent
variable. The following program can be executed in MATLAB to find a polynomial that best fits
this data.
In the above code, the value of a polynomial at a point x is calculated with the function
polyval which has the form:
73
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
x can also be a vector or a matrix. In such a case the polynomial is calculated for each element
(element-by-element), and the answer is a vector, or a matrix, with the corresponding values of
the polynomial.
This means that the polynomial of the third degree has the form 0.022x 3-0.4005x2+2.6138x-
1.4158.
iv. Curve Fitting with Functions Other than Polynomials
Many situations in science and engineering require fitting functions that are not polynomials to
given data. For a particular data set, however, some functions provide a better fit than others.
In addition, determining the best-fitting coefficients can be more difficult for some functions
than for others. This section covers curve fitting with power, exponential, logarithmic, and
reciprocal functions, which are commonly used. The forms of these functions are:
All of these functions can easily be fitted to given data with the polyfit function. This is done
by rewriting the functions in a form that can be fitted with a linear polynomial (n = 1), which is
y=mx+b
The logarithmic function is already in this form, and the power, exponential and reciprocal
equations can be rewritten as:
This means that the polyfit(x,y,1) function can be used to determine the best-fit
constants m and b for best fit if, instead of x and y, the following arguments are used.
74
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
The result of the polyfit function is assigned to p, which is a two-element vector. The first
element, p(1), is the constant m, and the second element, p(2), is b for the logarithmic and
reciprocal functions, ln(b) or log(b) for the exponential function, and ln(b) for the power
function (b=ep(2) or b=10p(2) for the exponential function, and b=ep(2) for the power function).
For given data it is possible to estimate, to some extent, which of the functions has the
potential for providing a good fit. This is done by plotting the data using different combinations
of linear and logarithmic axes. If the data points in one of the plots appear to fit a straight line,
the corresponding function can provide a good fit according to the list below.
75
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
c) PROCEDURE
1. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the software.
2. Open a new script file and write a program to determine a linear equation in the form TB
= mh + b that best fits the data in the following table (TB is the boiling temperature of
water and h is the corresponding altitude). Use the equation for calculating the boiling
temperature at 16000 ft. Make a plot of the points and the equation.
m= , b=
Boiling temperature at 16000 ft:
3. Open a new script file and write a program to determine an exponential function in the
form NB = Neαt that best fits the data in the following table (NB is the number of bacteria
measured at different times t). Use the equation to estimate the number of bacteria
after 60 min. Make a plot of the points and the equation.
α= , N=
Number of bacteria after 60 min:
4. Open a new script file and curve-fit the data of population of the world for selected
years from 1750 to 2009 in the following table with a third-order polynomial. Use the
polynomial to estimate the population in 1980. Make a plot of the points and the
polynomial.
76
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Open a new script file and write a program to determine the constants m and b by
curve-fitting the equation to the data points. Make a plot of P versus t. In the plot show
the data points with markers and the curve-fitted equation with a solid line. (The curve
fitting can be done by writing the reciprocal of the equation and using a first-order
polynomial.)
m= , b=
d) CONCLUSIONS
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
77
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT 10: INTERPOLATION IN MATLAB
a) EQUIPMENT
MATLAB software installed on your PC
b) THEORY
Interpolation is a procedure in which a mathematical formula is used to represent a given set of
data points, such that the formula gives the exact value at all the data points and an estimated
value between the points. For any number of points n there is a polynomial of order n -1 that
passes through all of the points. Once the polynomial is determined, it can be used for
estimating the y values between the known points simply by substituting for the x coordinate in
the polynomial.
i. Lagrange Interpolating Polynomials
Lagrange interpolating polynomials are a particular form of polynomials that can be written to
fit a given set of data points by using the values at the points. The polynomials can be written
right away and do not require any preliminary calculations for determining coefficients. The
general formula of an n-1 order Lagrange polynomial that passes through n points (x1, y1), (x2,
y2), ... , (xn, yn) is:
The above equation can be written in a compact form using summation and product notation
as:
The spacing between the data points does not have to be equal.
For a given set of points, the whole expression of the interpolation polynomial has to be
calculated for every value of x.
78
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
If the data set is enlarge to include additional points, all the terms of the Lagrange
polynomial have to be calculated again.
ii. Spline Interpolation
When a large number of points is involved, a better interpolation can be obtained by using
many low-order polynomials instead of a single high-order polynomial. Each low-order
polynomial is valid in one interval between two or several points. Typically, all of the
polynomials are of the same order, but the coefficients are different in each interval. When
first-order polynomials are used, the data points are connected with straight lines. For second-
order (quadratic), and third-order (cubic) polynomials, the points are connected by curves.
Interpolation in this way is called piecewise, or spline, interpolation.
MATLAB can interpolate using one of several methods that can be specified. These
methods include:
'nearest' returns the value of the data point that is nearest to the interpolated point.
'linear' uses linear spline interpolation (default).
'spline' uses cubic spline interpolation.
'pchip' also called 'cubic' , uses piecewise cubic Hermite interpolation.
When the 'nearest' and the 'linear' methods are used, the value(s) of xi must be
within the domain of x. If the ' spline' or the 'pchip' methods are used, xi can have
values outside the domain of x and the function interp1 performs extrapolation.
The ' spline' method can give large errors if the input data points are nonuniform
such that some points are much closer together than others.
79
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
c) PROCEDURE
11. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the software.
12. Open a new script file and save the following user-defined function for implementation
of Lagrange interpolation with the name LagrangeINT.m.
14. For the data points given in step 3, use linear and cubic spline interpolation in the
command window to determine the value of y at x=3 using interp1 function.
Yint for linear spline: ______________________
Yint for cubic spline: ______________________
15. In the command window, fit the data of population of the world for selected years from
1750 to 2009 in the following table with linear and spline interpolations. Estimate the
population in 1975 with linear and spline interpolations. Make a plot of the data points
(circle markers) and curves made of the interpolated points.
80
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Estimated population in 1975 using linear spline:
Estimated population in 1975 using cubic spline:
16. Measurements of the fuel efficiency of a car FE at various speeds v are shown in the
table.
Open a new script file. Estimate the fuel efficiency at 60 mi/h with Lagrange
interpolation. Fit the data with linear and spline interpolations and again estimate the
fuel efficiency at 60mi/h using linear and spline interpolations. Make two plots that
shows the data points and curves made of interpolated points.
d) CONCLUSIONS
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
81
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT 11: SOLVING A SYSTEM OF LINEAR EQUATIONS
a) EQUIPMENT
MATLAB software installed on your PC
b) THEORY
Systems of linear equations that have to be solved simultaneously arise in problems that
include several (possibly many) variables that are dependent on each other. A system of two (or
three) equations with two (or three) unknowns can be solved manually by substitution or other
mathematical methods (e.g., Cramer's rule). Solving a system in this way is practically
impossible as the number of equations (and unknowns) increases beyond three.
The matrix form of the equations is also shown. Two types of numerical methods, direct and
iterative, are used for solving systems of linear algebraic equations. In direct methods, the
solution is calculated by performing arithmetic operations with the equations. In iterative
methods, an initial approximate solution is assumed and then used in an iterative process for
obtaining successively more accurate solutions.
82
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
and
Now the system of equations Ax=b has been converted to LUx=b. To solve this, first we solve
Ly=b for y by forward-substitution method, then solve Ux=y for x by backward-substitution
method.
In the Gauss-Seidel method, the current values of the unknowns are used for calculating the
new value of the next unknown. In other words, as a new value of an unknown is calculated, it
is immediately used for the next application of above equation. Applying above equation to the
Gauss-Seidel method gives the iteration formula:
The iterations can be stopped when the absolute value of the estimated relative error of all the
unknowns is smaller than some predetermined value.
83
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
USE OF MATLAB BUILT-IN FUNCTIONS FOR SOLVING A SYSTEM OF LINEAR EQUATIONS
Left division \ : Left division can be used to solve a system of n equations written in matrix form
[a][x] = [b], where [a] is the (n x n) matrix of coefficients, [x] is an (n x 1) column vector of the
unknowns, and [b] is an (n x 1) column vector of constants.
Right division /: Right division is used to solve a system of n equations written in matrix form
[x][a] = [b], where [a] is the (n x n) matrix of coefficients, [x] is a ( 1 x n) row vector of the
unknowns, and [b] is a (1 x n) row vector of constants.
In MATLAB, the inverse of a matrix [a] can be calculated either by raising the matrix to the
power of -1 or by using the inv(a) function. Once the inverse is calculated, the solution is
obtained by multiplying the vector [b] by the inverse.
c) PROCEDURE
17. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the software.
18. Open a script file and write the following code for Doolittle’s method and save it as
DooLittle.m.
function [L U]=DooLittle(A)
[m,n]=size(A);
if m~=n
disp('Matrix must be square')
84
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
return
end
L=zeros(n);
U=zeros(n);
for k=1:n
L(k,k)=1;
for j=k:n
U(k,j)=A(k,j);
for s=1:k-1
U(k,j)=U(k,j)-L(k,s)*U(s,j);
end
end
for i=(k+1):n
L(i,k)=A(i,k);
for s=1:k-1
L(i,k)=L(i,k)-L(i,s)*U(s,k);
end
L(i,k)=L(i,k)/U(k,k);
end
end
19. Open two new script files and save the following codes for forward and backward
substitution separately in them with given names.
function y = ForwardSub(L,b)
% The function solves a system of linear equations ax = b
% where a is lower triangular matrix by using forward substitution.
% Input variables:
% a The matrix of coefficients.
% b A column vector of constants.
% Output variable:
% y A column vector with the solution.
n=length(b);
y(1,1)=b(1)/L(1,1);
for i=2:n
y(i,1)=(b(i)-L(i,1:i-1)*y(1:i-1,1))./L(i,i);
end
function y = BackwardSub(U,b)
% The function solves a system of linear equations ax = b
% where a is an upper triangular matrix by using back substitution.
% Input variables:
% a The matrix of coefficients.
% b A column vector of constants.
% Output variable:
% y A column vector with the solution.
n=length(b);
y(n,1)=b(n)/U(n,n);
for i=n-1:-1:1
y(i,1)=(b(i)-U(i,i+1:n)*y(i+1:n,1))./U(i,i); end
85
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
20. In the command window, solve the following system of linear equations using
DooLittle’s method i.e. use the previously defined three functions.
L= , U=
21. Open a new script file and copy the following code for solving the system in step 4 by
Gauss-Siedel method upto 7 iterations.
22. Execute the m-file and note the answer for the last iteration.
x1= _____________, x2=______________, x3=______________, x4= _____________
86
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
(a) Solve using DooLittle’s method in the command window.
L= , U=
(b) Solve by changing the code given in step 5 for the Gauss-Siedel method. Execute the
first five iterations and note result of last one.
x1= _____________, x2=______________, x3=______________
d) CONCLUSIONS
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
87
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT 12: NUMERICAL DIFFERENTIATION IN MATLAB
a) EQUIPMENT
MATLAB software installed on your PC
b) THEORY
Differentiation gives a measure of the rate at which a quantity changes. Rates of change of
quantities appear in many disciplines, especially science and engineering. One of the more
fundamental of these rates is the relationship between position, velocity, and acceleration.
The approach we’ll be considering is to use a finite difference approximation for the derivative.
A finite difference approximation of a derivative at a point xi is an approximate calculation
based on the value of points in the neighborhood of xi. This approach is illustrated in figure 13-
1, where the derivative at point xi is approximated by the slope of the line that connects the
point before xi with the point after xi.
Backward difference is the slope of the line that connects points (xi-1,f(xi-1)) and (xi,f(xi)):
88
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
ii. USE OF MATLAB BUILT-IN FUNCTIONS FOR NUMERICAL DIFFERENTIATION
MATLAB does not have built-in functions that perform numerical differentiation of an arbitrary
function or discrete data. There is, however, a built-in function called polyder, which
determines the derivative of polynomial. It can also calculate the derivative of a product and
quotient of two polynomials. The simplest form of the command is:
The only difference between the last two commands is the number of output arguments. With
two output arguments MATLAB calculates the derivative of the quotient of two polynomials.
With one output argument the derivative is of the product.
c) PROCEDURE
1. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the software.
2. Open a script file and write a MATLAB user-defined function that calculates the
derivative of a function that is given by a set of discrete points. Name the function
dx=derivative(x,y) where x and y are vectors with the coordinates of the points,
and dx is a vector with the value of the derivative dy/dx at each point. The function
should calculate the derivative at all points except the last using the forward finite
difference formulas while that at the last point with backward difference formula.
89
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
3. In the command window: use the given data points to calculate the velocity of the block
for 4 < t < 8 s. Calculate the acceleration of the block by differentiating the velocity.
Make a plot of the displacement, velocity, and acceleration, versus time for 4 < t < 8 s.
5.
Derivative of f(x):_____________________________
6.
Derivative of f1(x):_____________________________
Derivative of f1(x)* f2(x): _____________________________
Derivative of f1(x)/ f2(x): _____________________________
d) CONCLUSIONS
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
90
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT 13: NUMERICAL INTEGRATION IN MATLAB
a) EQUIPMENT
MATLAB software installed on your PC
b) THEORY
Integration is frequently encountered when solving problems and calculating quantities in engineering
and science. The general form of a definite integral (also called an antiderivative) is:
where f(x), called the integrand, is a function of the independent variable x, and a and b are the limits of
the integration. The value of the integral I(f) is a number when a and b are numbers. Graphically, as
shown in Figure 14-1, the value of the integral corresponds to the shaded area under the curve of f(x)
between a and b.
The integrand can be an analytical function or a set of discrete points (tabulated data). When the
integrand is a mathematical expression for which the antiderivative can be found easily, the value of the
definite integral can be determined analytically. Numerical integration is needed when analytical
integration is difficult or not possible, and when the integrand is given as a set of discrete points.
91
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Closed and Open methods
In closed integration methods, the endpoints of the interval (and the integrand) are used in the
formula that estimates the value of the integral. In open integration methods, the interval of
integration extends beyond the range of the endpoints that are actually used for calculating the
value of the integral. The trapezoidal and Simpson's methods studied in class are closed
methods and these will be our main concern in this lab.
ii. TRAPEZOIDAL METHOD
Substituting above equation into the general equation of a definite integral and integrating
analytically gives:
Simplifying the result gives an approximate formula popularly known as the trapezoidal rule or
trapezoidal method.
The integral over the interval [a, b] can be evaluated more accurately by dividing the interval
into subintervals, evaluating the integral for each subintervals (with the trapezoidal method),
and adding the results. As shown in figure 14-2, the interval [a, b] is divided into N subintervals
by defining the points x1, x2, ... , xn+1 where the first point is x1 = a and the last point is xn+1 = b (it
takes N + 1 points to define N intervals). The integral over the whole interval can be written as
the sum of the integrals in the subintervals:
92
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Applying the trapezoidal method to each subinterval [xi, xi+1] yields:
Substituting the trapezoidal approximation in the right side of above equation gives:
Above equation is the general formula for the composite trapezoidal method. If, however, the
subintervals are all the same width, that is, if
(1)
iii. SIMPSON’S 1/3 METHOD
The trapezoidal method described in the last subsection relies on approximating the integrand
by a straight line. A better approximation can possibly be obtained by approximating the
integrand with a nonlinear function that can be easily integrated. One class of such methods,
called Simpson's rules or Simpson's methods, uses quadratic (Simpson's 1/3 method) and cubic
(Simpson's 3/8 method) polynomials to approximate the integrand. We’ll only be discussing the
former one here.
93
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Figure 14-3: Simpson’s 1/3 method
where α, β and γ are unknown constants evaluated from the condition that the polynomial
passes through the points, p(x1) = f(x1), p(x2) = f(x2), and p(x3) = f(x3). These conditions yield:
where h = (b-a)/2 . Substituting the constants back in Eq., and integrating p(x) over the interval
[a, b] gives:
(2)
In the composite Simpson's 1/3 method the whole interval [a, b] is divided into N subintervals.
Since three points are needed for defining a quadratic polynomial, the Simpson's 1/3 method is
applied to two adjacent subintervals at a time (the first two, the third and fourth together, and
so on). Consequently, the whole interval has to be divided into an even number of subintervals.
The integral over the whole interval can be written as the sum of the integrals of couples of
adjacent subintervals.
By using equation (2), the integral over two adjacent intervals [xi-1, xi] and [xi, xi+1] can be
written in terms of the Simpson's 1/3 method by:
94
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
Evaluating last two equations gives:
(3)
It is important to point out that above equation can be used only if two conditions are satisfied:
• The subintervals must be equally spaced.
• The number of subintervals within *a, b+ must be an even number.
MATLAB has several built-in functions for carrying out integration. The following describes how
to use MATLAB's functions quad and trapz for evaluating single integrals. The quad
command is used to integrate functions, while the trapz function is used to integrate
tabulated data.
c) PROCEDURE
26. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the software.
27. Open a new script file and copy the following implementation of the trapezoidal method
in it saving it as a function file.
28.
(a) Change the trapezoidal function defined in step 2 for this problem i.e.
instead of integrating a function it takes the values of the function f(x) (second
row) as input. Use the altered function and in the command window calculate
the integral. Take N=6.
Answer: ______________________
Answer: ______________________
96
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
29. Open a new script file and with the help of trapezoidal function
implementation, implement the Simpson’s 1/3 method. The user defined function will
have the same input arguments as the trapezoidal function i.e.
I = Simpson13(Fun,a,b,N).
Using the following methods in the command window (change format to long):
(a) Use the Simpson13 function of step 4 with N=6. (sin2x will be defined as an
anonymous function).
Answer: ______________________
31.
97
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
32.
Use the trapz command and remember to convert velocity to ft/s (1 mi/h = 1.466ft/s).
Answer: ______________________
d) CONCLUSIONS
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
98
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
EXPERIMENT 14: ORDINARY DIFFERENTIAL EQUATIONS (INITIAL VALUE
PROBLEMS)
a) EQUIPMENT
MATLAB software installed on your PC
b) THEORY
A differential equation is an equation that contains derivatives of an unknown function. The
solution of the equation is the function that satisfies the differential equation. A differential
equation that has one independent variable is called an ordinary differential equation (ODE). A
first-order ODE involves the first derivative of the dependent variable with respect to the
independent variable. For example, if x is the independent variable and y is the dependent
variable, the equation has combinations of the variables x, y, and dy/dx. A first-order ODE is
linear, if it is dx a linear function of y and dy/dx (it can be a nonlinear function of x). Examples of
a linear and a nonlinear first-order ODE are given in following equations, respectively.
where a and b are constants. Differential equations provide detailed information regarding
distributions or variations of the dependent variable as a function of the independent variable.
In general, an infinite number of functions satisfy the equation. To obtain a specific solution, a
first-order ODE must have an initial condition or constraint that specifies the value of the
dependent variable at a particular value of the independent variable. Because such problems
are typically time-dependent problems (i.e., problems in which time t is the independent
variable), the constraint is called an initial condition and the problem is called an initial value
problem (IVP).
The solution is the function y(x) that satisfies the equation and the initial condition.
Numerical solution is a procedure for calculating an estimate of the exact solution at a set of
discrete points. The solution process is incremental, which means that it is determined in steps.
It starts at the point where the initial value is given. Then, using the known solution at the first
99
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
point, a solution is determined at a second nearby point. This is followed by a solution at a third
point, and so on. There are procedures with a single-step and multistep approach. In a single-
step approach, the solution at the next point, xi+1, is calculated from the already known solution
at the present point, xi. In a multi-step approach, the solution at xi+1 is calculated from the
known solutions at several previous points.
Single-step methods
In a single-step explicit method, the approximate numerical solution (xi+1, yi+1) is calculated from
the known solution at point (xi, yi) by:
where h is the step size, and the Slope is a constant that estimates the value of dy in the
interval from xi to xi+1. The numerical solution dx starts at the point where the initial value is
known. This corresponds to i = 1 and point (x1, y1). Then i is increased to i = 2, and the solution
at the next point, (x2, y2), is calculated by using above equations. The procedure continues with i
= 3 and so on until the points cover the whole domain of the solution.
Many single-step methods use the above equations. The difference between the methods is in
the value used for the constant Slope and in the way that it is determined. The simplest is
Euler's method, in which Slope is equal to the slope of y(x) at (xi, yi). A more sophisticated class
of methods, called Runge-Kutta methods, is also presented. In these methods the value of Slope
is calculated from a weighted average of estimates of the slope of y(x) at several points within
an interval.
i. EULER’S METHOD
Euler's method is a single-step numerical technique for solving a first-order ODE. The method
uses the equations previously defined, where the value of the constant Slope is the slope of y(x)
at point (xi, yi). This slope is actually calculated from the differential equation:
Euler's method assumes that for a short distance h near (xi, yi), the function y(x) has a constant
slope equal to the slope at (xi, yi). With this assumption, the next point of the numerical solution
(xi+1, yi+1) is calculated by:
(1)
(2)
100
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
ii. RUNGE-KUTTA METHODS
Runge-Kutta methods are a family of single-step numerical techniques for solving a first-order
ODE. For a subinterval (step) defined by [xi, xi+1], where h = xi+1- xi, the value of yi+1 is calculated
by:
where Slope is a constant. The value of Slope in above equation is obtained by considering the
slope at several points within the subinterval. Various types of Runge-Kutta methods are
classified according to their order. The order identifies the number of points within the
subinterval that are used for determining the value of Slope. Second-order Runge-Kutta
methods use the slope at two points, third-order methods use three points, and so on.
Runge-Kutta methods give a more accurate solution compared to the simpler Euler's method.
In each step, however, they require several evaluations (depending on the order) of the func-
tion for the derivative f(x, y).
where c1, c2, a2, and b21 are constants. The values of these constants vary with the specific
second-order method. For the modified Euler method, the constants are:
iv. USE OF MATLAB BUILT-IN FUNCTION FOR SOLVING INITIAL VALUE PROBLEMS
MATLAB has several built-in functions that can be used for solving a single first-order ODE. The
differences between the various built-in functions are in the numerical methods used for the
101
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
solution. The procedure for solving a first-order ODE with MATLAB is summarized in the
following list.
Three pieces of information are needed for solving a first-order ODE: an equation that gives an
expression for the derivative of y with respect to t, the interval of the independent variable, and
the initial value of y. An example is:
The ODE to be solved has to be written as a user-defined function (in a function file) or as an
anonymous function. Both calculate for given values of t and y. For the example problem
above, the user-defined function (which is saved as a separate file) is:
When an anonymous function is used, it can be defined in the Command Window, or be within
a script file. For the example problem here the anonymous function (named ode1) is:
The following table lists several of the built-in functions available in MATLAB for solving a first-
order ODE. A short description of the numerical method used in each built-in function is
included in the table.
102
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
In general, the solvers can be divided into two groups according to their ability to solve stiff
problems and according to whether they use on-step or multi-step methods. Stiff problems are
ones that include fast and slowly changing components and require small time steps in their
solution. One-step solvers use information from one point to obtain a solution at the next
point. Multistep solvers use information from several previous points to find the solution at the
next point. It is impossible to know ahead of time which solver is the most appropriate for a
specific problem. We will only be using ode45 as it gives good results for many problems.
The form of the command that is used to solve an initial value ODE problem is the same for all
the solvers and for all the equations that are solved. The form is:
where:
solver_name is the name of the solver (numerical method) that is used (e.g.ode45 or
ode23s)
ODEfun The function from Step 2 that calculates for given values of t and y. If it
was written as a user-defined function, the function handle is entered. If it was written as an
anonymous function, the name of the anonymous function is entered.
tspan A vector that specifies the interval of the solution. The vector must have
at least two elements but can have more. If the vector has only two elements, the elements
must be [t0 tf], which are the initial and final points of the solution interval. The vector
tspan can have, however, additional points between the first and last points. The number of
elements in tspan affects the output from the command. See [t,y] below.
103
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
y0 The initial value of y (the value of y at the first point of the interval).
[t,y] The output, which is the solution of the ODE. t and y are column vectors.
The first and the last points are the beginning and end points of the interval. The spacing and
number of points in between depends on the input vector tspan. If tspan has two elements
(the beginning and end points), the vectors t and y contain the solution at every integration
step calculated by the solver. If tspan has more than two points (additional points between
the first and the last), the vectors t and y contain the solution only at these points.
For example, consider the solution to the problem stated in Step 1. If the ODE function is
written as a user-defined function (see Step 2), then the solution with MATLAB’s built-in
function ode45 is obtained by:
If the ODE function is written as an anonymous function called ode1 (see Step 2), then the
solution (same as shown above) is obtained by typing:
[t y]=ode45(ode1,[1:0.5:3],4.2)
c) PROCEDURE
1. Switch on your computer and double-click on the MATLAB icon on the desktop to launch
the software.
2. Open a new script file and copy the following code in it. Name the function file as
odeEULER.m.
104
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
3.
Write a MATLAB program in a script file that solves the equation using h = 0.1 and
h=0.01. The equation dy/dx can be used by defining an anonymous function. Also plot
the exact and numerical results for both values of h side by side in the same figure,
where the exact solution is:
4. In a script file, solve the ODE given in step 3, using MATLAB’s built-in function ode45.
When defining tspan use a step size of 0.5 and again with 0.25. Plot the exact and
numerical result for both step sizes where the exact solution is same as given in step 3.
Which step size gives more accurate result?
105
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB
5.
Using odeEULER with h=0.01 and ode45 with same step size. Plot both solutions on the
same graph.
6.
The solution is the current in the inductor as a function of time. Solve for for 0<t<0.4s using
ode45 function with a step size of 0.001. Plot vs and iL versus time (make two separate plots on
the same page).
d) CONCLUSIONS
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Name: ________________________
Registration No.: _______________
Teacher’s Initials: _______________
Date: _________________________
106
NUMERICAL ANALYSIS
FACULTY OF ENGINEERING, UNIVERSITY OF CENTRAL PUNJAB