You are on page 1of 71

EG264

Computer Aided Engineering


EG228
Civil Laboratory III (MATLAB)
K. Morgan
School of Engineering
University of Wales Swansea
First Semester
20062007
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 14 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 followthe timetable for your laboratory classes, as these rooms only provide a limited number
of PCs.
Ofce Hours
In weeks 811, I will be available, to discuss any problems that are specically related to this course,
on Tuesdays, between 1400 and 1450, in my ofce, Room 163 of the Talbot Building. Alternatively,
I can be contacted at the email address k.morgan@swansea.ac.uk
1
GENERAL INFORMATION
Module Objectives
1. To increase your level of condence 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 efciency 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 startprograms mathsMATLAB
3
GENERAL INFORMATION
Assessment
You are asked to submit your MATLAB solution to a specied 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 6770 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 le will not be sufcient 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 supercial 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 dont leave the project work until the last minute.
4. The concepts in this course are not difcult, but ensure that you allow yourself the necessary
time to produce the required computerbased solutions.
5. Use the library, the online MATLAB help facility and Internet based resources to provide you
with additional support; in particular, you can nd 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)
log
10
x log10(x)
log
e
x log(x)
e
x
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.
Noninteger 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 formis used if the signicant 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 4
5 6 7 8
9 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 =
_

_
a
1,1
a
1,2
a
1,m1
a
1,m
a
2,1
a
2,2
a
2,m1
a
2,m
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
a
n1,1
a
n1,2
a
n1,m1
a
n1,m
a
n,1
a
n,2
a
n,m1
a
n,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 =
_

_
7
3
2
5
_

_
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 xed 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 3
4
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 = x
2
for 1 x 2
we rst 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 2
0
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 2
0
0.5
1
1.5
2
2.5
3
3.5
4
Test plot
x
y
=
x
2
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
4
linear
quadratic
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 L
A
T
E
X, can be accomplished by using File and then Export
on the graphics window toolbar.
22
MATLAB: mFILES & FLOW CONTROL
Function mFiles
For complicated problems, the simple use of the command window becomes inappropriate and
a better approach is to create a text le, called an mle, that contains the series of MATLAB
commands that are to be executed.
We begin by considering a function mle which has all problem specic variables dened and with
all commands operating on variables that exist in the workspace.
If the commands are entered into a le named example, the le should be stored with the extension
.m i.e. as example.m.
MATLAB provides its own editor for creating and modifying mles.
This can be accessed under File on the command windowtoolbar and selecting Open for an existing
le and New > Mle if a new le is to be created.
23
MATLAB: mFILES & FLOW CONTROL
Working Directory
Create a new directory, say EG228 files or EG264 files.
Use this directory to store your MATLAB les.
You may wish to create further subdirectories as your work progresses.
You must tell MATLAB in which directory to store and to nd the les you are using.
Do this by specifying the directory path.
When this has been done, the commands in the mle 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: mFILES & FLOW CONTROL
Specifying the Directory Path

25
MATLAB: mFILES & FLOW CONTROL
Example
The analyis of a three pin semicircular arch of radius, R, under uniform load, W. The variation of
the bending moment, M, with angle, , is
M = WR
2
[0.5(1.0 sin) +( 0.5) cos ]
A function mle 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 mle arch.m and running it again.
For example
26
MATLAB: mFILES & 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
0
Bending moment distribution
theta (degrees)
M
27
MATLAB: mFILES & FLOW CONTROL
Flow Control
In a general function mle, 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 ow features for this situation.
If Statement
Allows a group of commands to be executed only if a certain logical test is satised.
For example, given a scalar variable x, we might want to evaluate a related variable y according to
y =
_
3 +2x
2
if x > 5
3 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: mFILES & FLOW CONTROL
Logical Operators
The logical operators that can be employed within ow 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 owcontrol commands are the if/else command, the if/elseif/else command
and the while command.
29
MATLAB: mFILES & 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: mFILES & FLOW CONTROL
Subfunctions
A function mle may contain other functions, called subfunctions, which may appear in any order
after the main function.
These subfunctions are only visible to each other and to the main function.
Subfunctions 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 mle 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
specic function that needs to be plotted in a subfunction.
A function mle func plot.m that would achieve this could employ the commands
31
MATLAB: mFILES & 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: mFILES & 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: mFILES & 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: mFILES & 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 rst \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 mle.
35
NUMERICAL METHODS OF INTEGRATION
The Denite Integral
The geometrical denition of the denite 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)
x
x=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 MidPoint Rule
This is based upon the approximation
f(x) f([a +b]/2) for a x b
Using this approximation in the denite 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)
x
x=a x=b x=(a+b)/2
f([a+b]/2)
h=b-a
37
NUMERICAL METHODS OF INTEGRATION
The Composite MidPoint Rule
The accuracy achieved may be improved by employing the composite form of the midpoint rule.
The interval [a, b] is subdivided into n nonoverlapping subintervals, each of length h, so that
h = (b a)/n.
We dene the end points of the intervals to be x
1
, x
2
, , x
n
, x
n+1
where
x
1
= a
x
2
= a +h
.
.
.
.
.
.
x
n
= a +(n 1)h
x
n+1
= a +nh = b
and note that
I =
_
b
a
f(x) dx =
_
x
2
x
1
f(x) dx +
_
x
3
x
2
f(x) dx + +
_
x
n
x
n1
f(x) dx +
_
x
n+1
x
n
f(x) dx
38
NUMERICAL METHODS OF INTEGRATION
f(x)
x
x=a x=b
x
x x x 1 2 3
4
f([x1+x2]/2)
f([x2+x3]/2)
f([x3+x4]/2)
h h h
Using the basic midpoint rule for each subinterval in turn produces the composite midpoint rule
approximation
I =
_
b
a
f(x) dx hf ([x
1
+x
2
] /2) +hf ([x
2
+x
3
] /2) + +hf ([x
n
+x
n+1
] /2)
where, now,
h = (b a)/n
39
NUMERICAL METHODS OF INTEGRATION
Using the Composite MidPoint 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 subintervals, until the accuracy attained is considered
sufcient.
Generally, the number of intervals, n, employed is successively doubled, so that the subinterval
length, h, is successively halved.
Algorithm for the Composite MidPoint Rule
Before we can begin to develop a MATLAB procedure for integrating a given function by the com-
posite midpoint 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 midpoint rule can be written as follows:
40
NUMERICAL METHODS OF INTEGRATION
1. the function, f(x), to be integrated is dened in a subfunction;
2. dene the lower and upper limits of the integration, a, b;
3. dene the number of subintervals n;
4. set h = (b a)/n;
4. approximate the integral by the composite midpoint rule:
(a) set integral = 0;
(b) consider each subinterval 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 midpoint 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 mle midpoint.m contains a MATLAB version of the composite midpoint 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 dened in a subfunction.
The function mle, with its subfunction, 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 subintervals, this produces the results 19147.5, 19318.1, 19360.8, 19371.4 re-
spectively.
These gures imply that for 8, 16, 32 subintervals, 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 specied 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 a
x for a x b
Using this approximation in the denite integral, we obtain
I =
_
b
a
f(x) dx
_
b
a
_
bf(a) af(b)
b a
+
f(b) f(a)
b a
x
_
dx =
h
2
(f(a) +f(b))
where h = b a.
f(x)
x
x=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 nonoverlapping subintervals, each of length h = (ba)/n.
The end points of the intervals are located at x
1
, x
2
, , x
n
, x
n+1
where
x
1
= a
x
2
= a +h
.
.
.
.
.
.
x
n
= a +(n 1)h
x
n+1
= a +nh = b
Again we use the result
I =
_
b
a
f(x) dx =
_
x
2
x
1
f(x) dx +
_
x
3
x
2
f(x) dx +
_
x
n+1
x
n
f(x) dx
and employ the simple trapezoidal rule over each subinterval in turn.
47
NUMERICAL METHODS OF INTEGRATION
f(x)
x
x=a x=b
x x x x 1 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 (x
1
) +f (x
2
)] + +
h
2
[f (x
n
) +f (x
n+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 midpoint rule.
The value of the approximation is recomputed using more and more subintervals, until the accuracy
attained is considered sufcient.
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 midpoint rule, as follows:
1. dene the function, f(x), to be integrated in a subfunction;
2. dene the lower and upper limits of the integration, a, b;
49
NUMERICAL METHODS OF INTEGRATION
3. dene the number of subintervals n;
4. set h = (b a)/n;
4. approximate the integral by the composite trapezoidal rule:
(a) set integral = 0;
(b) consider each subinterval 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 xed, the
solution is expressed in terms of the scalar variable x, where x satises 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), dened 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
x x=a
x=b
y=f(x)
y
x
y=f(x)
x=a
x=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 x
m
= (a + b)/2, which lies midway
between the points x = a and x = b, given that f(a) f(b) 0. This is the rst estimate of the
root and the maximum error in this estimate is (b a)/2.
If f(a) f(x
m
) 0, the root lies between x = a and x = x
m
. The new estimate of the root is
(a +x
m
)/2 and the maximum error in this estimate is (x
m
a)/2.
If f(a) f(x
m
) > 0, the root lies between x = x
m
and x = b. The new estimate of the root is
(x
m
+b)/2 and the maximum error in this estimate is (b x
m
)/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 specied 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. dene the function, f(x), in a subfunction;
2. dene the number n of bisection steps to be used;
3. dene two points, a and b, such that f(a) f(b) 0;
4. dene initial interval by x left = a, x right = b;
5. dene 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 maximumabsolute
error in this estimate as (x right x left)/2.0;
A more sophisticated MATLAB implementation would automatically continue the interval subdivision
process until a specied accuracy level is achieved.
55
NUMERICAL METHODS OF ROOT FINDING
The NewtonRaphson method
In the NewtonRaphson method, we dont 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 x
0
.
y
x
x x
0
1
y=f(x)
y=f(x )
0
root
tangent at x=x
0
We compute both f(x
0
) and its derivative f

(x
0
) and draw in the tangent to the graph at x = x
0
.
This tangent passes through the point (x
0
, f(x
0
)) and has slope f

(x
0
), so its equation is
y f(x
0
)
x x
0
= f

(x
0
)
56
NUMERICAL METHODS OF ROOT FINDING
This line cuts the xaxis at the point x = x
1
when y = 0, so that
f(x
0
)
x
1
x
0
= f

(x
0
)
which implies that
x
1
= x
0

f(x
0
)
f

(x
0
)
The gure 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 x
1
, x
2
, x
3
, from the
equation
x
j+1
= x
j

f(x
j
)
f

(x
j
)
j = 0, 1, 2,
The convergence of the NewtonRaphson method is much faster than that of the bisection method.
However, the quality of the initial guess, x
0
, is crucial and bad choices can lead to divergence of the
iteration process.
57
LABORATORY 1
Objectives
The objectives of this rst 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 mles;
4. start to run your own function mles, 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 (f
1
, f
2
) of the stress f across a surface, with normal in a direction
making an angle with the x axis, are given to be
f
1
=
(
x
+
y
)
2
+
(
x

y
)
2
cos 2 +
xy
sin2
f
2
=
(
x

y
)
2
sin2 +
xy
cos 2
and the principal stresses are

+
=
(
x
+
y
)
2
+
_
_

x

y
2
_
2
+
2
xy

=
(
x
+
y
)
2

_
_

x

y
2
_
2
+
2
xy
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 f
1
and f
2
when = 30 degrees;
[27772, 64130.9]
(c) the values of f
1
and f
2
when = 80 degrees.
[35879.9, 10720.6]
59
LABORATORY 1
1.2 A certain high strength concrete has a Youngs modulus E = 31 units and a Poisons 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 mle 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 A
N
of the rst N terms in an arithmetic progression is known to be given by
A
N
= 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 A
100
given by the formula.
60
LABORATORY 1
1.4 The sum G
N
of the rst N terms in a geometric progression is known to be given by
G
N
= a +ar +ar
2
+ +ar
N1
=
a
_
1 r
N
_
1 r
Use a for loop to compute
0.1 +0.1 0.2 +0.1 0.2
2
+ +0.1 0.2
100
and compare your result with the value of G
101
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/s
2
. A certain parachutist has a drag coefcient 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
147/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 =
F
0

2

2
0
_ [ sin(
0
t)
0
sin(t)]
where F
0
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 mle forced.m that, for dened values of and
0
, produces a plot of
the variation of x/F
0
for values of t in the range 0 t 500. Use this mle with the dened 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 mle that produces the roots of the quadratic equation
ax
2
+bx +c = 0
for dened values of the coefcients 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 mle 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 x
1
= 0.2679, x
2
= 3.7321]
(c) a = 4, b = 1, c = 1; [complex roots x
1
= 0.125 +0.4841i, x
2
= 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 mles located centrally on the Engineering PC network into your own work area;
2. develop your condence in the process of creating, storing and editing function mles;
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 mle midpoint.m. A subfunction in this le denes a function f(x). Running this
function mle enables the numerical integration of f(x) over a prescribed range by the composite midpoint
rule. The le 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 subfunction so that it denes f(x) = x
3
. Run the function mle midpoint.m and see how many
intervals are required to ensure that the composite midpoint rule produces an approximation to the integral of x
3
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/30
dz
Use the composite midpoint 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 mle midpoint.m and the algorithmic steps outlined in these notes, write
a new function mle trapez.m that provides the approximation to the integral of a dened function, over a
prescribed range, by the composite trapezoidal rule. Include the capability for automatically determining the
number of subintervals 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 mle 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 rst two laboratories and to ensure that
you
1. gain further experience in the process storing and editing function mles;
2. gain some experience in the process of root nding;
3. gain additional experience in writing your own function mle 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 mle 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 dened in a subfunction.
65
LABORATORY 3
2. Use bisection.m, with a prescribed number of bisection steps, to obtain the values of x for which x
2
= 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 le bisection.m to ensure that an approximation to the root with a prescribed absolute error is
automatically obtained. This function mle will be needed again later for your project submission.
4. For uid ow in pipes, the dimensionless friction factor, f, is related to the Reynolds number, R, by the von
Karman equation
1
_
f
= 4log
10
_
R
_
f
_
0.4
Write a function mle, 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 specied 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 conrm 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 les (i.e. NOT re-typed by you);
4. a listing of the actual output from MATLAB giving the answers requested (i.e. NOT retyped
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 les: 5 marks.
Submission Details
Solutions may be submitted to me personally, in Room 163 of the Talbot Building, at any time. The
nal deadline for submission is 12 noon on Friday December 15th, 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 marks.
Late submissions due to certicated 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 nonlinear
spring. The other end of the spring is xed.
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) = k
1
x
a
+k
2
x
b
where k
1
, k
2
, 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,
k
1
(1 +a)
d
(a+1)
+
k
2
(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
k
1
= 40000 (1 +u) k
2
= 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
k
1
= 400000 k
2
= 64000 m = 1140 g = 10.29
h = 0.516 a = 1.04 b = 1.59
70

You might also like