Matlab tutorial advanced
description
Transcript of Matlab tutorial advanced
EG–264Computer Aided Engineering
EG–228Civil Laboratory III (MATLAB)
K. MorganSchool of Engineering
University of Wales Swansea
First Semester2006–2007
GENERAL INFORMATION
Lectures & Computer Laboratory Classes
There are 2 one hour lecture slots allocated to this course in the timetable.
These slots will be used in weeks 1–4 only.
Each student will attend three computer laboratory classes between week 2 and week 7.
The computer laboratory classes will be held on Tuesdays from 1400 to 1550 in Rooms 43a and 47.
Please follow the timetable for your laboratory classes, as these rooms only provide a limited number
of PCs.
Office Hours
In weeks 8–11, I will be available, to discuss any problems that are specifically related to this course,
on Tuesdays, between 1400 and 1450, in my office, Room 163 of the Talbot Building. Alternatively,
I can be contacted at the e–mail address [email protected]
1
GENERAL INFORMATION
Module Objectives
1. To increase your level of confidence in the use of MATLAB;
2. To introduce you to a wider range of capabilities of MATLAB;
3. To illustrate to you how MATLAB can be used to assist the process of undertaking certain basic
engineering calculations.
2
GENERAL INFORMATION
What is MATLAB?
MATLAB (MATrix LABoratory) is a software package for interactive numerical computation, graph-
ics and data analyis. It provides engineers with a versatile platform for solving a wide range of
computational problems.
General advantages of MATLAB over other packages include:
1. greater efficiency for problems involving matrices;
2. a wider range of intrinsic functions and toolboxes are supported;
3. greater versatility for problems involving loops and decisions;
4. better graphics.
Availability of MATLAB
MATLAB may be accessed under your account on the School of Engineering PC network by follow-
ing the path start→programs→ maths→MATLAB
3
GENERAL INFORMATION
Assessment
You are asked to submit your MATLAB solution to a specified problem. This will be worth 40% of
the total marks available for the complete module.
The requirements of the project are set out in detail on pages 67–70 of these notes.
Academic Honesty
Read the sections on unfair practice and plagiarism in the School of Engineering and the University
Handbooks.
Students are encouraged to work together on the course examples and to study in groups to help
each other learn the material.
However, you are expected to submit for marking only work that represents your own efforts.
Note that simply changing the variable names in a MATLAB file will not be sufficient to hide the fact
that two solutions are essentially the same.
Programming style tends to be very individualistic: similarities in style and formatting will always be
apparent, even if superficial changes are made.
Consider this carefully before giving your work to a colleague to ‘help them out’.
4
GENERAL INFORMATION
General Advice
1. Improving your MATLAB technique will only be possible if you have a good general knowledge
of MATLAB.
2. Spend some extra time early in the semester to familiarize yourself with the format of MATLAB.
3. Complete the laboratory work promptly and don’t leave the project work until the last minute.
4. The concepts in this course are not difficult, but ensure that you allow yourself the necessary
time to produce the required computer–based solutions.
5. Use the library, the on–line MATLAB help facility and Internet based resources to provide you
with additional support; in particular, you can find an introductory tutorial and a lot of further
helpful information at http://www.mathworks.co.uk/academia
5
MATLAB: BASICS
MATLAB Desktop
6
MATLAB: BASICS
Command Window
• located within the desktop;
• displays the prompt >>;
• displays a blinking cursor to the right of the prompt, when the window is active.
MATLAB as a Calculator
Working in the command window, MATLAB may be used as a calculator to perform basic mathe-
matical calculations by typing MATLAB statements.
A MATLAB statement consists of mathematical operators, numbers, mathematical functions and
(perhaps) variable names.
7
MATLAB: BASICS
Mathematical Operators
Operation MATLAB operator
Addition +
Subtraction -
Multiplication *
Division /
Exponentiation ^
Variable Names
In MATLAB, variable names can contain up to 31 characters and
1. are case sensitive, i.e. a and A are different variables;
2. must start with a letter followed by any number of letters, digits or underscores (punctuation
characters are not allowed).
Note that certain names are not allowed, e.g. for end if, as they are already used by MATLAB.
8
MATLAB: BASICS
Some Mathematical Functions
MATLAB provides a large number of mathematical functions.
Examples of some commonly used functions and their MATLAB equivalents are:
Function MATLAB form
sin x sin(x)
cos x cos(x)
tan x tan(x)
|x| abs(x)
log10 x log10(x)
loge x log(x)
ex exp(x)√
x sqrt(x)
Note that in the evaluation of sin, cos, tan, the argument is expressed in radians.
9
MATLAB: BASICS
MATLAB Statements
A statement is normally terminated with the return key.
A statement can be continued on to the next line by using ... followed by a return.
An example of a MATLAB statement could be
0.5*((6.2)^3)
Here, the result is displayed on the screen and is assigned to the variable ans, which is automatically
created.
Alternatively, a statement can take the form
a=0.5*((6.2)^3)
Here, the result is displayed on the screen and assigned to the variable a for future use.
Several statements may be included in the same line, provided that they are separated by commas
or semicolons.
If a statement is followed by a semicolon, the display to the screen is suppressed, but the assign-
ment is still performed.
10
MATLAB: BASICS
Display Formats
MATLAB stores numbers and performs calculations with a relative precision of about 16 places of
decimals.
By default, integer values are displayed as integers.
Non–integer values are normally displayed with up to four digits to the right of the decimal point and
up to three digits to the left e.g. 3.1416 or 131.9274
The exponent form is used if the significant digits in the result lie outside this range e.g. 1315.926784
would be displayed as 1.3159e+003 and 0.00007643526 would be displayed as 7.6435e-005
Different display styles can be selected by using the format command. This command has many
options and these can be examined by typing help format e.g. following the use of the command
format long all values will be displayed with about 16 digits.
11
MATLAB: BASICS
Useful Commands
To get help on a command, type help plus the command name.
To get more general MATLAB help, look under MATLAB help on the pull down menu under help on
the desktop.
who provides a list of the variables that have been created in the command window. The current
value of a variable may be found by typing the variable name.
clear removes all variables from the memory.
clc clears the command window.
clf clears the graphics window.
Typing the Ctrl key with the c key interrupts the MATLAB statement execution.
12
MATLAB: BASICS
Command Line Recall and Editing
Up/down arrows may be used to scroll through your list of previous commands, so that a previous
command line can be recalled, edited and the revised command submitted.
To edit a command line, position the cursor with the left/right arrows. Backspace (or Delete) may be
used to delete the character to the left of the cursor. Characters can also be inserted in this fashion.
13
MATLAB: MATRICES & GRAPHICS
Matrix Variables
A matrix is a rectangular array of numbers.
Matrix variables can be named using the same rules as applied in the allocation of simple variable
names.
A 3 × 4 matrix
A =
1 2 3 45 6 7 89 10 11 12
can be entered into MATLAB with the command
>> A=[1,2,3,4;5,6,7,8;9,10,11,12]
or
>> A=[1,2,3,4;
5,6,7,8;
9,10,11,12];
Note that matrix elements in a row are separated by commas and the rows are separated by semi-
colons.
14
MATLAB: MATRICES & GRAPHICS
Matrix Operations
If two matrices A and B are the same size, their sum C can be found with the command
>> C=A+B
If A is n × m and B is m × ℓ, their product D is n × ℓ and can be found with the command
>> D=A*B
The Subscript Notation
Using the subscript notation, the entries in an n × m matrix A may be represented in the form
A =
a1,1 a1,2 · · · a1,m−1 a1,m
a2,1 a2,2 · · · a2,m−1 a2,m... ... . . . ... ...
an−1,1 an−1,2 · · · an−1,m−1 an−1,m
an,1 an,2 · · · an,m−1 an,m
Similarly, in MATLAB A(2,3) refers to the entry in the matrix variable A in the second row and the
third column.
15
MATLAB: MATRICES & GRAPHICS
Vectors
Vectors are ordered lists of numbers. The row vector
x = [5,7,3,2,1]
and the column vector
y =
7325
can be entered into MATLAB with the commands
>> x=[5,7,3,2,1];
>> y=[7;3;2;5];
Now x(4) is equal to 2 and y(2)=3.
16
MATLAB: MATRICES & GRAPHICS
Setting Special Vectors
Vectors whose entries increase at a constant rate may be conveniently constructed in a number of
ways. For example, to set up a vector of length 11, with entries x(1)=0.0, x(2)=0.1, x(3)=0.2,
......., x(11) =1.0, we can use
(a) the statement x=0.0:0.1:1.0;
(b) the statement x=linspace(0.0,1.0,11);
(c) the for loop
for i=1:11
x(i)=(i-1)*0.1;
end
A for loop allows a command, or a group of commands, to be repeated a fixed number of times.
17
MATLAB: MATRICES & GRAPHICS
Basic Plotting
If x and y are vectors of the same length, the plot command may be used to plot the values in y
against the corresponding values in x i.e. for each j, the point with coordinates x(j) and y(j) is
plotted and successive points are joined with straight line segments.
For example, using the commands
>> x=[1,2,3];y=[4,6,5];
>> plot(x,y)
produces
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 34
4.2
4.4
4.6
4.8
5
5.2
5.4
5.6
5.8
6
18
MATLAB: MATRICES & GRAPHICS
Basic Plotting
To plot a general function, such as
y = x2 for − 1 ≤ x ≤ 2
we first use a for loop to set up a list of values of x with the corresponding values of y.
As successive points will be joined by straight line segments, we need to employ enough x values
to ensure that the resulting graph appears smooth.
Here, we set up 31 values of x, equally spaced by amount 0.1, on the interval −1 ≤ x ≤ 2, and
determine the corresponding values of y using the for loop
>> for i=1:31
x(i)=-1+(i-1)*0.1;
y(i)=x(i)^2;
end
Then
>> plot(x,y)
produces
−1 −0.5 0 0.5 1 1.5 20
0.5
1
1.5
2
2.5
3
3.5
4
19
MATLAB: MATRICES & GRAPHICS
Further Enhancements
The addition of a title and the labelling of the axes can be achieved as in the following example:
>> for i=1:31
x(i)=-1+(i-1)*0.1;
y(i)=x(i)^2;
end
>> plot(x,y)
>> title(’Test plot’)
>> xlabel(’x’)
>> ylabel(’y=x^2’)
−1 −0.5 0 0.5 1 1.5 20
0.5
1
1.5
2
2.5
3
3.5
4Test plot
x
y=x2
20
MATLAB: MATRICES & GRAPHICS
Further Enhancements
The command plot clears the graphics window before drawing the graph. To prevent this, the
command hold on holds the current graph.
The default is to plot solid lines, but other line styles are also possible.
The command legend can then be used to distinguish between the different graphs.
>> for i=1:31
x(i)=-1+(i-1)*0.1;
yl(i)=x(i);
yq(i)=x(i)^2;
end
>> plot(x,yq,’-.’)%dash/dot line style
>> hold on
>> plot(x,yl,’:’)%dotted line style
>> %label the lines
>> legend(’quadratic’,’linear’)−1 −0.5 0 0.5 1 1.5 2
−1
−0.5
0
0.5
1
1.5
2
2.5
3
3.5
4linearquadratic
21
MATLAB: MATRICES & GRAPHICS
Exporting Graphs to Other Applications
Graphs can be exported to other applications in a number of ways.
Copying a graph into a WORD document is easily accomplished by selecting Edit and then Copy
Figure on the graphics window toolbar.
If the WORD document is then opened, the graph may be inserted at the desired location by means
of the Paste command.
Exporting in eps format, e.g. for use with LATEX, can be accomplished by using File and then Export
on the graphics window toolbar.
22
MATLAB: m–FILES & FLOW CONTROL
Function m–Files
For complicated problems, the simple use of the command window becomes inappropriate and
a better approach is to create a text file, called an m–file, that contains the series of MATLAB
commands that are to be executed.
We begin by considering a function m–file which has all problem specific variables defined and with
all commands operating on variables that exist in the workspace.
If the commands are entered into a file named example, the file should be stored with the extension
.m i.e. as example.m.
MATLAB provides its own editor for creating and modifying m–files.
This can be accessed under File on the command window toolbar and selecting Open for an existing
file and New > M–file if a new file is to be created.
23
MATLAB: m–FILES & FLOW CONTROL
Working Directory
Create a new directory, say EG228 files or EG264 files.
Use this directory to store your MATLAB files.
You may wish to create further sub–directories as your work progresses.
You must tell MATLAB in which directory to store and to find the files you are using.
Do this by specifying the directory path.
When this has been done, the commands in the m–file example.m can be executed by entering
>> example
in the command window or by clicking the Run button on the editor tool bar.
24
MATLAB: m–FILES & FLOW CONTROL
Specifying the Directory Path
25
MATLAB: m–FILES & FLOW CONTROL
Example
The analyis of a three pin semi–circular arch of radius, R, under uniform load, W. The variation of
the bending moment, M , with angle, θ, is
M = WR2 [0.5π(1.0 − sin θ) + (θ − 0.5π) cos θ]
A function m–file arch.m can be written to plot the variation of M with θ, for prescribed values of R
and W .
If the distribution of M is required for different values of R and W , this can be readily obtained by
editing the function m–file arch.m and running it again.
For example
26
MATLAB: m–FILES & FLOW CONTROL
function arch
%arch semi--circular arch under uniform load: distribution of bending moment
clc;clear;clf;
%specify arch radius, uniform load, no. plot points
R=30.0;W=80.0;np=201;
%vector of theta values, zero to 180 (degrees)
for i=1:101
theta(i)=(i-1)*180/(np-1);
%corresponding theta1 value(radians)
theta1=pi*theta(i)/180;
%corresponding bending moment values
M(i)=W*(R^2)*(0.5*pi*(1.0-sin(theta1))...
+(theta1-0.5*pi).*cos(theta1));
end
%plot the moment diagram
plot(theta,M), title(’Bending moment distribution’)
xlabel(’theta(degrees)’), ylabel(’M’)
0 20 40 60 80 100 120 140 160 180−9000
−8000
−7000
−6000
−5000
−4000
−3000
−2000
−1000
0Bending moment distribution
theta (degrees)
M
27
MATLAB: m–FILES & FLOW CONTROL
Flow Control
In a general function m–file, we may encounter the situation that the order in which the commands
are to be executed depends upon the values assigned to certain variables.
MATLAB provides a number of different control flow features for this situation.
If Statement
Allows a group of commands to be executed only if a certain logical test is satisfied.
For example, given a scalar variable x, we might want to evaluate a related variable y according to
y =
{
3 + 2x2 if x > 53 otherwise
This can be achieved by the commands
%set the value of y
y=3.;
%reset the value of y if x>5
if x>5
y=3.+2.0*x^2
end
28
MATLAB: m–FILES & FLOW CONTROL
Logical Operators
The logical operators that can be employed within flow control statements are
Relational Operator Logical Operation
> greater than
>= greater than or equal
< less than
<= less than or equal
== equal
∼= not equal
Alternative Flow Control Commands
Note that other available flow control commands are the if/else command, the if/elseif/else command
and the while command.
29
MATLAB: m–FILES & FLOW CONTROL
Terminating Loops
MATLAB provides the break command for terminating for and while loops e.g. the commands
for i=1:2500
if i <= 10
x(i)=i;
else
break
end
end
create a vector x of length 10, with entries
x(1)=1, x(2)=2,.......,x(10)=10
30
MATLAB: m–FILES & FLOW CONTROL
Sub–functions
A function m–file may contain other functions, called sub–functions, which may appear in any order
after the main function.
These sub–functions are only visible to each other and to the main function.
Sub–functions can accept and return arguments in exactly the same fashion as the standard MAT-
LAB functions, such as sin, cos, etc.
Consider the problem of writing an m–file to plot any function of the form f(x) over a prescribed
range a ≤ x ≤ b.
It could be convenient to write a main function that works for any function f(x) and to describe the
specific function that needs to be plotted in a sub–function.
A function m–file func plot.m that would achieve this could employ the commands
31
MATLAB: m–FILES & FLOW CONTROL
function func_plot
%=======================================================================
%func_plot plots the form of the function f(x) over the
% prescribed range a < x < b
% the function f(x) is defined in a sub-function
%======================================================================
clear
clf
%======================================================================
%define the range for plotting
%======================================================================
a=0.0; b=20.0;
%======================================================================
32
MATLAB: m–FILES & FLOW CONTROL
%=====================================================================
%define the number of sampling points
%=====================================================================
n=1000;
%======================================================================
%set up the array of x values and the corresponding values of f(x)
%======================================================================
for i=1:n+1
x(i)=a+(i-1)*(b-a)/n;
f_plot(i)=f(x(i));
end
%======================================================================
%plot the function
%======================================================================
plot(x,f_plot)
%======================================================================
33
MATLAB: m–FILES & FLOW CONTROL
%======================================================================
%sub-function
%======================================================================
function [f_value]=f(x)
%=====================================================================
%f(x) evaluates x*sin(x)
%=====================================================================
f_value=x*sin(x)
%=====================================================================
0 2 4 6 8 10 12 14 16 18 20−20
−15
−10
−5
0
5
10
15
20
34
MATLAB: m–FILES & FLOW CONTROL
Labelling Output and Printing Numerical Values
Computed results can be displayed and text can be printed using the fprintf command e.g. sup-
pose that the variables x and y have the values 2.53456123 and 1.21694723 respectively and we
want these values printed in the command window and labelled. The command
fprintf(’\n Value of x = %g Value of y = %g\n’,x,y)
produces the output
Value of x = 2.53456 Value of y =1.21695
In this command statement, the incorporation of the first \n ensures that the output appears on a
new line, while the use of each %g ensures that the numerical values of the variables x and y are
displayed in the most convenient format. The second \n provides a blank line before the appearance
of the results produced by the next fprintf command in the m–file.
35
NUMERICAL METHODS OF INTEGRATION
The Definite Integral
The geometrical definition of the definite integral
I =
∫ b
a
f(x) dx
is that it is equal to the area under the curve y = f(x), between the end points x = a and x = b.
f(x)
xx=a x=b
If the integration can not be performed analytically, numerical integration methods can be used to
approximate the value of the integral.
Numerical methods of integration are based upon techniques that produce approximations, in some
sense, to the area under the curve.
36
NUMERICAL METHODS OF INTEGRATION
The Simple Mid–Point Rule
This is based upon the approximation
f(x) ≈ f([a + b]/2) for a ≤ x ≤ b
Using this approximation in the definite integral, we obtain the result
I =
∫ b
a
f(x) dx ≈∫ b
a
f([a + b]/2)dx = (b − a)f([a + b]/2) = hf([a + b]/2)
where h = b − a.
f(x)
xx=a x=bx=(a+b)/2
f([a+b]/2)
h=b-a
37
NUMERICAL METHODS OF INTEGRATION
The Composite Mid–Point Rule
The accuracy achieved may be improved by employing the composite form of the mid–point rule.
The interval [a, b] is subdivided into n non–overlapping sub–intervals, each of length h, so that
h = (b − a)/n.
We define the end points of the intervals to be x1, x2, · · · , xn, xn+1 where
x1 = a
x2 = a + h... ...
xn = a + (n − 1)h
xn+1 = a + nh = b
and note that
I =
∫ b
a
f(x) dx =
∫ x2
x1
f(x) dx +
∫ x3
x2
f(x) dx + · · · +∫ xn
xn−1
f(x) dx +
∫ xn+1
xn
f(x) dx
38
NUMERICAL METHODS OF INTEGRATION
f(x)
xx=a x=bx x x x1 2 3 4
f([x1+x2]/2)
f([x2+x3]/2)
f([x3+x4]/2)
h h h
Using the basic mid–point rule for each sub–interval in turn produces the composite mid–point rule
approximation
I =
∫ b
a
f(x) dx ≈ hf ([x1 + x2] /2) + hf ([x2 + x3] /2) + · · · + hf ([xn + xn+1] /2)
where, now,
h = (b − a)/n
39
NUMERICAL METHODS OF INTEGRATION
Using the Composite Mid–Point Rule
In the standard mode of operation, the approximation to the value of the integral is recomputed using
the composite rule with more and more sub–intervals, until the accuracy attained is considered
sufficient.
Generally, the number of intervals, n, employed is successively doubled, so that the sub–interval
length, h, is successively halved.
Algorithm for the Composite Mid–Point Rule
Before we can begin to develop a MATLAB procedure for integrating a given function by the com-
posite mid–point rule, we need to develop a step by step description of the process.
Such a step by step description is termed an algorithm.
An algorithmic description for the composite mid–point rule can be written as follows:
40
NUMERICAL METHODS OF INTEGRATION
1. the function, f(x), to be integrated is defined in a sub–function;
2. define the lower and upper limits of the integration, a, b;
3. define the number of sub–intervals n;
4. set h = (b − a)/n;
4. approximate the integral by the composite mid–point rule:
(a) set integral = 0;
(b) consider each sub–interval i in turn 1 ≤ i ≤ n;
(i) compute the end points of the interval x left = a + (i − 1) ∗ h, x right = a + i ∗ h;
(ii) compute the mid–point of the interval, x half = (x left + x right)/2.0;
(iii) evaluate the function at this point, f half = f(x half);
(ii) add the contribution from the interval to the integral as
integral = integral + f half ∗ h
41
NUMERICAL METHODS OF INTEGRATION
MATLAB Implementation
The function m–file midpoint.m contains a MATLAB version of the composite mid–point rule al-
gorithm and approximates the integral of a function between prescribed limits, using a prescribed
number of intervals. The function to be integrated is defined in a sub–function.
The function m–file, with its sub–function, may be copied to your MATLAB folder from drive G, on
the Engineering PC network, following the path MATLAB → work → EG228 or EG264.
function midpoint
%==========================================================================
% midpoint mid-point rule for approximate numerical integration
% of a defined function, f(x)
% between defined limits, a and b
% prescribed number of sub-intervals, n
%=========================================================================
clear
clc
%=========================================================================
42
NUMERICAL METHODS OF INTEGRATION
%=========================================================================
%define the integration limits
%=========================================================================
a=5.0; b=10.0;
%=======================================================================
%define the number of sub-intervals to be used
%=======================================================================
n=4;
%=======================================================================
h=(b-a)/n; integral=0.0;
%======================================================================
43
NUMERICAL METHODS OF INTEGRATION
%=======================================================================
%add the contribution of each sub-interval in turn
%=======================================================================
for i=1:n;
x_left=a+(i-1)*h;
x_right=a+i*h;
x_half=(x_left+x_right)/2.0;
f_half=f(x_half);
integral=integral+h*f_half;
end;
%========================================================================
%print the approximation to the value of the integral
%==========================================================================
fprintf(’\n Approximation to integral using %g subintervals is %g’,n,integral);
%==========================================================================
44
NUMERICAL METHODS OF INTEGRATION
%==========================================================================
%sub-function
%==========================================================================
function [f_value]=f(x)
%==========================================================================
%f(x) provides the value of the function f=x^4 at the point x
%==========================================================================
f_value=x^4;
%==========================================================================
For 4, 8, 16, 32 sub–intervals, this produces the results 19147.5, 19318.1, 19360.8, 19371.4 re-
spectively.
These figures imply that for 8, 16, 32 sub–intervals, the estimated relative error is 0.88%, 0.22%,
0.05% respectively.
This means that 32 intervals would be needed in this case, if the value of the integral was required
with a relative error of less than 0.1%. A more sophisticated MATLAB implementation would perform
this interval doubling automatically until a specified error level was achieved.
45
NUMERICAL METHODS OF INTEGRATION
The Simple Trapezoidal Rule
This is a different numerical integration technique and is based upon approximating the function
f(x) by the linear function that is equal to f(x) at the two end points of the range i.e.
f(x) ≈ bf(a) − af(b)
b − a+
f(b) − f(a)
b − ax for a ≤ x ≤ b
Using this approximation in the definite integral, we obtain
I =
∫ b
a
f(x) dx ≈∫ b
a
[
bf(a) − af(b)
b − a+
f(b) − f(a)
b − ax
]
dx =h
2(f(a) + f(b))
where h = b − a.
f(x)
xx=a x=b
h=b-a
f(a)f(b)
46
NUMERICAL METHODS OF INTEGRATION
The Composite Trapezoidal Rule
For accurate approximation to the value of the integral, the composite form of the trapezoidal rule is
used.
The interval [a, b] is subdivided into n non–overlapping sub–intervals, each of length h = (b−a)/n.
The end points of the intervals are located at x1, x2, · · · , xn, xn+1 where
x1 = ax2 = a + h
... ...xn = a + (n − 1)h
xn+1 = a + nh = b
Again we use the result
I =
∫ b
a
f(x) dx =
∫ x2
x1
f(x) dx +
∫ x3
x2
f(x) dx · · · +∫ xn+1
xn
f(x) dx
and employ the simple trapezoidal rule over each sub–interval in turn.
47
NUMERICAL METHODS OF INTEGRATION
f(x)
xx=a x=bx x x x1 2 3 4
f(x1)
f(x2)
f(x4)
h h h
f(x3)
This produces the composite trapezoidal rule approximation
I =
∫ b
a
f(x) dx ≈ h
2[f (x1) + f (x2)] + · · · + h
2[f (xn) + f (xn+1)]
where
h = (b − a)/n
48
NUMERICAL METHODS OF INTEGRATION
Using the Composite Trapezoidal Rule
The standard mode of operation for the composite trapezoidal rule will be similar to that employed
for the composite mid–point rule.
The value of the approximation is recomputed using more and more sub–intervals, until the accuracy
attained is considered sufficient.
Algorithm for the Composite Trapezoidal Rule
An algorithmic description of the steps involved in the composite trapezoidal rule may be obtained,
by modifying the algorithm given earlier for the composite mid–point rule, as follows:
1. define the function, f(x), to be integrated in a sub–function;
2. define the lower and upper limits of the integration, a, b;
49
NUMERICAL METHODS OF INTEGRATION
3. define the number of sub–intervals n;
4. set h = (b − a)/n;
4. approximate the integral by the composite trapezoidal rule:
(a) set integral = 0;
(b) consider each sub–interval i in turn 1 ≤ i ≤ n;
(i) compute the end points of the interval x left = a + (i − 1) ∗ h, x right = a + i ∗ h;
(ii) evaluate the function at these points
f left = f(x left) f right = f(x right)
(iii) add the contribution from the interval to the integral as
integral = integral + (h/2.0) ∗ (f left + f right)
50
NUMERICAL METHODS OF ROOT FINDING
Typical Problem
When modelling the buckling of a strut of length ℓ, with one end pinned and the other end fixed, the
solution is expressed in terms of the scalar variable x, where x satisfies the equation
xℓ = tan(xℓ)
The value of x will normally be obtained by a numerical approximation method.
In a numerical approach, we introduce the function f(x), defined here by
f(x) = xℓ − tan(xℓ)
and then look for values of x such that
f(x) = 0
These x values are called the roots of the equation and these roots are the solutions of the original
problem.
If we take a set of axes and plot the graph of
y = f(x)
the points at which the graph cuts the x axis are the required roots.
51
NUMERICAL METHODS OF ROOT FINDING
The Bisection Method
To produce a rough estimate of the location of a root, we use the fact that if f(x) is continuous
between x = a and x = b and if f(a) and f(b) have opposite signs, then f(x) has at least one
root between a and b.y
xx=ax=b
y=f(x)
y
x
y=f(x)
x=ax=b
The bisection method is based upon the continued use of this concept to produce an accurate
approximation to the value of the root.
52
NUMERICAL METHODS OF ROOT FINDING
The basic idea is to evaluate the function f(x) at the point xm = (a + b)/2, which lies midway
between the points x = a and x = b, given that f(a) ∗ f(b) ≤ 0. This is the first estimate of the
root and the maximum error in this estimate is (b − a)/2.
If f(a) ∗ f(xm) ≤ 0, the root lies between x = a and x = xm. The new estimate of the root is
(a + xm)/2 and the maximum error in this estimate is (xm − a)/2.
If f(a) ∗ f(xm) > 0, the root lies between x = xm and x = b. The new estimate of the root is
(xm + b)/2 and the maximum error in this estimate is (b − xm)/2.
Thus we have located the root to lie in an interval which is half as large as the previous interval.
This process is continued for a specified number of steps, with the interval length halved at each
step. At the end of the process, the root is located within an interval of a certain length and the
maximum error in the estimate of the root is equal to one half the current interval length.
Algorithm for the Bisection Method
An algorithmic description of the steps involved in determining a root of the equation f(x) = 0 by
the bisection method may be expressed as follows:
53
NUMERICAL METHODS OF ROOT FINDING
1. define the function, f(x), in a sub–function;
2. define the number n of bisection steps to be used;
3. define two points, a and b, such that f(a) ∗ f(b) ≤ 0;
4. define initial interval by x left = a, x right = b;
5. define the value of f(x) at these points as f left = f(x left), f right = f(x right);
6. at each bisection step i, for 1 ≤ i ≤ n:
(a) set x mid = (x left + x right)/2.0;
(b) compute f mid = f(x mid);
54
NUMERICAL METHODS OF ROOT FINDING
(c) if f left ∗ f mid ≤ 0 then:
(i) change the interval boundary as x right = x mid;
(ii) change the function value at x right as f right = f mid;
(d) if f left ∗ f mid > 0:
(i) change the interval boundary as x left = x mid;
(ii) change the function value at x left as f left = f mid;
(e) print the current estimate of the root as (x left+x right)/2.0 and the maximum absolute
error in this estimate as (x right − x left)/2.0;
A more sophisticated MATLAB implementation would automatically continue the interval sub–division
process until a specified accuracy level is achieved.
55
NUMERICAL METHODS OF ROOT FINDING
The Newton–Raphson method
In the Newton–Raphson method, we don’t compute a sequence of nested intervals that bracket the
root but a sequence of points that, hopefully, converges to the root.
We start with an initial guess for the root, which we call x0.
y
xxx
01
y=f(x)
y=f(x )0
root
tangent at x=x0
We compute both f(x0) and its derivative f ′(x0) and draw in the tangent to the graph at x = x0.
This tangent passes through the point (x0, f(x0)) and has slope f ′(x0), so its equation is
y − f(x0)
x − x0
= f ′(x0)
56
NUMERICAL METHODS OF ROOT FINDING
This line cuts the x–axis at the point x = x1 when y = 0, so that
−f(x0)
x1 − x0= f ′(x0)
which implies that
x1 = x0 − f(x0)
f ′(x0)
The figure suggests that this should be an improved estimate of the value of the root.
This process can be continuously repeated, constructing a set of points x1, x2, x3, · · · from the
equation
xj+1 = xj −f(xj)
f ′(xj)j = 0,1,2, · · ·
The convergence of the Newton–Raphson method is much faster than that of the bisection method.
However, the quality of the initial guess, x0, is crucial and bad choices can lead to divergence of the
iteration process.
57
LABORATORY 1
Objectives
The objectives of this first laboratory are to ensure that you
1. can locate the MATLAB software on the Engineering PC network;
2. are able to use MATLAB as a calculator, using variable names to store the results of intermediate calculations;
3. begin to familiarise yourself with the process of creating, storing and editing function m–files;
4. start to run your own function m–files, producing results and plots.
Task Schedule
To enable you to meet these objectives you should work through the following examples. If you are unable to complete
all these during the time allocated for this laboratory, you should try and complete them in your own time before your
next scheduled laboratory class.
58
LABORATORY 1
1.1 In a certain elastic solid, the components (f1, f2) of the stress f across a surface, with normal in a direction
making an angle θ with the x axis, are given to be
f1 =(σx + σy)
2+
(σx − σy)
2cos2θ + τxy sin 2θ
f2 = −(σx − σy)
2sin 2θ + τxy cos 2θ
and the principal stresses are
σ+ =(σx + σy)
2+
√
(
σx − σy
2
)2
+ τ2xy
σ− =(σx + σy)
2−
√
(
σx − σy
2
)2
+ τ2xy
If σx = 83100kPa, σy = −28400kPa and τxy = −31700kPa, determine, using MATLAB as a calculator,
(a) the values of the principal stresses σ+ and σ−;
[91482.3, −36782.3]
(b) the values of f1 and f2 when θ = 30 degrees;
[27772, −64130.9]
(c) the values of f1 and f2 when θ = 80 degrees.
[−35879.9, 10720.6]
59
LABORATORY 1
1.2 A certain high strength concrete has a Young’s modulus E = 31 units and a Poison’s ratio ν = 0.20. If the
Cartesian strains are given to be
ǫxx = −400 × 10−6 ǫyy = −800 × 10−6 ǫzz = −1200 × 10−6 γxy = −750 × 10−6
create a MATLAB m–file to determine the stress components from the expressions
σxx =E
(1 − 2ν)(1 + ν)[(1 − ν)ǫxx + ν (ǫyy + ǫzz)]
σyy =E
(1 − 2ν)(1 + ν)[(1 − ν)ǫyy + ν (ǫzz + ǫxx)]
τxy =E
2(1 + ν)γxy
[−0.031, −0.0413333, −0.0096875]
1.3 The sum AN of the first N terms in an arithmetic progression is known to be given by
AN = 1 + 2 + 3 + · · · + N =N(N + 1)
2
Use a for loop to compute
1 + 2 + 3 + ....... + 100
and compare your result with the value of A100 given by the formula.
60
LABORATORY 1
1.4 The sum GN of the first N terms in a geometric progression is known to be given by
GN = a + ar + ar2 + · · · + arN−1 =a(
1 − rN)
1 − r
Use a for loop to compute
0.1 + 0.1 ∗ 0.2 + 0.1 ∗ 0.22 + · · · + 0.1 ∗ 0.2100
and compare your result with the value of G101 given by the formula.
1.5 The velocity v of a falling parachutist, of mass m, is given, at time t after the start of the fall, by
cv
mg= 1 − e−ct/m
where g = 9.8m/s2. A certain parachutist has a drag coefficient c = 14kg/s and attains a velocity v = 35m/s at
time t = 7s. Using MATLAB, plot in the same graphics window, graphs of
y =14 ∗ 35
m ∗ 9.8
and
y = 1 − e−14∗7/m
for values of m in the range 60 < m < 70 and hence obtain an approximate value for the mass m of the
parachutist. The use of the grid on command can help in estimating the required value from the graphics
window.
[m ≈ 63.5kg]
61
LABORATORY 1
1.6 The displacement x(t) of a forced, undamped, oscillating spring mass system is given to be
x =F0
ω(
ω2 − ω20
) [ω sin (ω0t) − ω0 sin (ωt)]
where F0 is the amplitude of the forcing function, ω is the natural frequency of the system and ω0 is the frequency
of the forcing function. Write a function m–file forced.m that, for defined values of ω and ω0, produces a plot of
the variation of x/F0 for values of t in the range 0 ≤ t ≤ 500. Use this m–file with the defined values ω = 1
and ω0 = 2, 1.2 and 1.02 in turn. The plots produced should illustrate the phenomenon of beats for the case
ω0 = 1.02, with the amplitude of the oscillation exhibiting a sinusoidal oscillation.
1.7 Write a function m–file that produces the roots of the quadratic equation
ax2 + bx + c = 0
for defined values of the coefficients a, b and c. The output should be labelled and distinguish between the cases
of equal roots, two real roots and two complex roots.
Use this m–file to determine the roots for the cases
(a) a = 1, b = 2, c = 1; [equal roots x = −1]
(b) a = 1, b = 4, c = 1; [real roots x1 = −0.2679, x2 = −3.7321]
(c) a = 4, b = 1, c = 1; [complex roots x1 = −0.125 + 0.4841i, x2 = −0.125 − 0.4841i]
Note how MATLAB automatically handles any complex numbers that appear.
62
LABORATORY 2
Objectives
The objectives of this second laboratory are to ensure that you
1. can copy m–files located centrally on the Engineering PC network into your own work area;
2. develop your confidence in the process of creating, storing and editing function m–files;
3. gain some experience in the process of numerical integration.
Task Schedule
To enable you to meet these objectives you should undertake the following tasks:
1. Obtain a copy of the function m–file midpoint.m. A sub–function in this file defines a function f(x). Running this
function m–file enables the numerical integration of f(x) over a prescribed range by the composite mid–point
rule. The file may be copied to your MATLAB folder from drive G on the Engineering PC network by following the
path MATLAB → work → EG228 or EG264.
63
LABORATORY 2
2. Change the sub–function so that it defines f(x) = x3. Run the function m–file midpoint.m and see how many
intervals are required to ensure that the composite mid–point rule produces an approximation to the integral of x3
over the range 0 ≤ x ≤ 2, with an absolute error of less than 0.001. Perform the integration exactly and compare
the exact answer with your approximation.
3. In a model of a racing sailboat, the total force, F , on the mast is expressed in the integral form
F =
∫ 30
0
200
(
z
5 + z
)
e−2z/30dz
Use the composite mid–point rule to approximate the value of F with a relative error of less than 1%.
[100 intervals: 1480.72; 200 intervals: 1480.61. Relative error much less than 1%]
4. Using the structure of the function m–file midpoint.m and the algorithmic steps outlined in these notes, write
a new function m–file trapez.m that provides the approximation to the integral of a defined function, over a
prescribed range, by the composite trapezoidal rule. Include the capability for automatically determining the
number of sub–intervals required to achieve an approximation with a prescribed relative error. This function will
be needed again later for your project submission.
5. Validate your new function m–file by repeating the integration exercises that you have carried out with the mid–
point rule and compare the results you obtain.
64
LABORATORY 3
Objectives
This third laboratory aims to build upon the work you have undertaken in the first two laboratories and to ensure that
you
1. gain further experience in the process storing and editing function m–files;
2. gain some experience in the process of root finding;
3. gain additional experience in writing your own function m–file to produce a desired result.
Task Schedule
To enable you to meet these objectives you should aim to undertake the following tasks:
1. Using the algorithmic steps outlined in these notes as a guide, write a function m–file bisection.m that, given a
function y(x), determines an estimate to the value x, in the range a ≤ x ≤ b, such that y(x) = 0. The values of
a and b should be prescribed in bisection.m and the function y(x) should be defined in a sub–function.
65
LABORATORY 3
2. Use bisection.m, with a prescribed number of bisection steps, to obtain the values of x for which x2 = 2.
Investigate how many bisection steps are needed to ensure that these x values are located to within an absolute
error of less than 0.001.
3. Modify your file bisection.m to ensure that an approximation to the root with a prescribed absolute error is
automatically obtained. This function m–file will be needed again later for your project submission.
4. For fluid flow in pipes, the dimensionless friction factor, f , is related to the Reynolds number, R, by the von
Karman equation
1√
f= 4 log10
(
R√
f
)
− 0.4
Write a function m–file, based on the bisection method, to provide an approximation to the value of f when
R = 100,000 with an absolute error < 5 × 10−8. You may assume that the root lies somewhere in the interval
0.001 ≤ f ≤ 0.05. [0.00450041]
66
PROJECT REQUIREMENTS
Basic Details
You are asked to submit your MATLAB solution to the problems specified below. The maximum
mark that can be attained is 40% of the total marks available for the complete module.
A professional presentation of your solution is required. This should contain
1. a cover page giving your name and your student number and including the signed statement
”I confirm that I have not received help from, or given help to, anyone else in constructing the
solution to this assignment”;
2. a brief description of the problem and of the process you have followed to produce your solu-
tion;
3. a complete documented listing of your actual MATLAB files (i.e. NOT re-typed by you);
4. a listing of the actual output from MATLAB giving the answers requested (i.e. NOT re–typed
by you);
5. appropriate referencing to any publication or web based material that you have used in con-
structing your solution.
67
PROJECT REQUIREMENTS
Marking
Marks will be awarded as follows:
1. the quality of the submitted work: 15 marks;
2. the accuracy of the results: 20 marks;
3. the MATLAB techniques used to obtain the solutions, the ease of understanding of the output
and the quality of the documentation within the MATLAB files: 5 marks.
Submission Details
Solutions may be submitted to me personally , in Room 163 of the Talbot Building, at any time. The
final deadline for submission is 12 noon on Friday December 15 th, 2006 (End of Week 11) . I
will hand you a receipt as proof that you have met the submission deadline.
Work that is submitted late will normally be awarded zero mar ks .
Late submissions due to certificated illness will be dealt with according to standard procedures.
68
PROJECT REQUIREMENTS
The Problems To be Solved
A block of mass m g is released at a distance h m above one end of a certain vertical non–linear
spring. The other end of the spring is fixed.
1. The force, F (x), in the spring when it is compressed by an amount x m by the mass is given
to be
F (x) = k1xa + k2x
b
where k1, k2, a and b are constants. Produce a plot, showing the variation of F with x, for
0 ≤ x ≤ 5h.
2. Conservation of energy can be used to show that, at equilibrium,
k1
(1 + a)d(a+1) +
k2
(1 + b)d(b+1) = mgd + mgh
where d is the compression of the spring. Use the bisection method to determine an approxi-
mation to the value of d, with an absolute error of less than 1 × 10−6.
69
PROJECT REQUIREMENTS
3. The energy E stored in the spring, at equilibrium, may be expressed in the form
E =
∫ d
0
F (x)dx
Use the composite trapezoidal rule to obtain an approximation to the value of E, with a relative
error of less than 0.001%.
Note the 6 digits uvwxyz of your student number. You should then use the parameter values
k1 = 40000 ∗ (1 + u) k2 = 8000 ∗ (1 + v) m = 950 ∗ (1.2 − 0.1 ∗ w)
h = 0.43 ∗ (1 + 0.1 ∗ x) g = 9.8 ∗ (1 + 0.01 ∗ y)
a = 1 + 0.01 ∗ z b = 1.5 + 0.01 ∗ u
To illustrated the process of creating the problem data, suppose your student number is 970254. In this case, u = 9,
v = 7, w = 0, x = 2, y = 5 and z = 4. Your solution should then be for the parameter values
k1 = 400000 k2 = 64000 m = 1140 g = 10.29
h = 0.516 a = 1.04 b = 1.59
70