Sunteți pe pagina 1din 26

Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I

Handout 1: MATHEMATICAL MODELLING


NUMERICAL 1.2 Introduction
METHODS FOR 1.1 Conservation law
1.3 An example of a simple mathematical model
ENGINEERS 1.4 Numerical methods: an example
COEB 223
PART I : INTRODUCTION & MATLAB
Dr. Hanim Salleh
Department of Mechanical Engineering
Universiti Tenaga Nasional
2007/2008
1 2
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
1.1 Introduction
Change = 0 = Increases – Decreases;
What is mathematical modelling? STEADY-STATE systems
∴ Increases = Decreases
• It is a way of expressing physical systems (phenomena,
processes, etc.) in mathematical terms • Some examples of engineering systems governed by conservation
laws:
• A Mathematical Model is an expression or equation that shows
the relationship between physical quantities involved in the  Fluid flow in pipes: conservation of mass
problems under consideration. It usually has the following  Electric circuit: conservation of energy and charge
form:  A moving body: conservation of force and momentum
- an example follows
Y = f { X, P, F }
1.3 An example of a simple mathematical
Where: model
Y is the dependent variable Let us consider a simple model to determine the ‘terminal velocity’ of a
X is the independent variables, freely falling parachutist.
P is the parameters and
F is the forcing functions Forces acting on the parachutist are –
The above equation implies that if we are given values of X, P and F and
1. FD, the Gravitational Force and
we know the relationships of these quantities with Y, we can then
2. Fv the viscous force or the force due to air resistance.
ATTEMPT to solve for Y.
According to Newton’s Second Law F = m.a i.e.:
So, first of all, how do we go about finding such relationships among the
quantities?
dv F
= (1)
dt M
1.2 Conservation law
F = FD + Fv (2)
• Basically, it’s a law saying that all the quantities (forces, mass,
etc.) in a particular system must be balanced, i.e. put simply: with FD = Mg and Fv = −cv
Change = Increases - Decreases TRANSIENT systems where c = Drag coefficient and
g = Acceleration due to gravity
In some special cases, when there is no change in the system, we can say dv Mg − cv
= (3)
that dt M
dv c
=g− v (4)
dt M
3 4
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
This can be integrated analytically using calculus as:  c 
v(ti+1 ) = v(ti ) +  g − v(ti )(ti+1 − ti )
 m 
gm
v(t ) = (1 − e −( c / m ) t ) (5)
c Note that this is actually a solution technique known as the EULER’S
method – we will see this in more details later in the course. Starting with
Equation (5) is in the form usually referred to as the ANALYTICAL or t1 = 0 and v(t1) = 0 and letting the step size be 2 s.
the EXACT solution for a given problem. Using this equation, we can
also calculate v for any time t. The results can be tabulated and a graph  12 .5 
v ( t 2 ) = 0 + 9 .8 − 0 ( 2 ) = 19 .60 m / s
of v against t can be plotted, as shown in Figure 1.1.  68 .1 
Time, t, s Velocity, v m/s  12 . 5 
v ( t 3 ) = 19 . 60 +  9 . 8 − (19 . 60 )  ( 2 ) = 32 . 00 m / s
0 0.00  68 . 1 
2 16.40
4 27.77 Continuing for the rest of the time t, we then have:
6 35.64
8 41.10 Time, t, s Velocity, v m/s
10 44.87 0 0.00
12 47.49 2 19.60
∞ 53.39 4 32.00
6 39.85
8 44.82
In the above problem, the situation is quite simple that the solution can be 10 47.97
derived analytically. What if there is no analytical solution? For example, 12 49.96
what if equation (4) cannot be integrated to give equation (5)? In this case ∞ 53.39
we must resort to using NUMERICAL METHODS in order to solve the
problem. This results in a solution that we call a NUMERICAL solution. As can be seen, the solution is in the form of numbers at a selected
number of discrete points - not an equation as in the analytical solution in
1.4 Numerical solution: an example equation (5). Using the above table, we can plot the solution and compare
it to the one obtained using the analytical solution. The comparison is
Looking at equation (4), the solution requires an approximation for the shown in Figure 1.2.
derivative dv/dt. Using a FINITE DIFFERENCE approximation,
An important point to note is that the numerical results are close to the
dv ∆v v(t ) − v (t i ) analytical results but are not 100% accurate. We can for example
≅ = i +1
dt ∆t t i +1 − t i improve the solution by reducing the step size from 2 s to 1s or 0.5 s.
The known drawbacks, however, are in terms of the computing times and
Therefore, substituting into (4), we have effort. We will deal more with these issues as we go further in this course.
dv v (ti +1 ) − v (ti ) c
= = g − v (ti )
dt ti +1 − ti m
Rearranging the terms:
5 6
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
As a general rule, there is usually a trade-off between effort and accuracy
and as we can expect – the more accurate the solution is, the greater effort Handout 2: Introduction to MATLAB
is needed to obtain it.
MATLAB fundamentals
Figure 1.1 2.1 Introduction
2.2 MATLAB environment
2.3 Assignment of values to variable names
2.4 Use of built-in functions
Figure 1.2
Next topic - Chapter 2: Programming
using MATLAB
7 8
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
creates a 1-by-1 matrix named A, which is then given a value of 3 in its single
element. Note that MATLAB treats names in case-sensitive manner.
2.1 Introduction Note that the use of semi-colon at the end of a statement is a characteristic of
MATLAB. It is used to suppress the ‘echo’ of the statement, i.e. if you remove the
• The name MATLAB stands for MATrix LABoratory. It is a high- semi-colon, you will have
performance language that integrates computation, visualization, and
programming in an easy-to-use environment. >> A = 3
• The MATLAB environment uses basic data element in the form of arrays. For
this reason, problems involving matrix and vector formulations can be A=
computed accurately and efficiently.
• MATLAB also has an excellent graphics representation capability, which 3
assists greatly in analysing and understanding the computed problems.
• MATLAB comes with a family of toolboxes. These are collections of >>
MATLAB functions (M-files) that extend MATLAB capabilities, enabling the
user to solve specific groups of problems. Examples include signal processing, To define a row vector,
control systems, wavelets, and curve fitting among others.
• Some areas in which MATLAB is used: >> A= [1 2 3 4 5]
 General mathematical calculations
 Programming - algorithm development A=
 Modelling, simulation, and prototyping
 Data analysis, presentation and visualization 1 2 3 4 5
 Application development, including graphical user interface (GUI)
building >>
A column vector can be defined using
2.2 The MATLAB environment
>> A = [1 ; 2; 3 ;4; 5]
Refer to figures 2.1- 2.4, together with the related descriptions.
A=
1
2.3 Assignment of values to variable names 2
3
Assignment of values to scalar variables is similar to other computer languages, with 4
one important distinction, however. In MATLAB, the mathematical expressions 5
involve entire matrices, and MATLAB does not require any type declarations or
dimension statements – once a new variable is encountered, it automatically creates or simply by using the transpose operator `’`,
the variable and allocates the appropriate amount of storage. For example, typing
>> A = [1 2 3 4 5]'
>> A = 3;
A=
1
2
3
4
5
In a similar fashion, we can write a matrix, row by row, using the following command
10
9 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
>> A= [1 2 3; 4 5 6; 7 8 9]
Trigonometric
A=
sin - Sine.
1 2 3 sinh - Hyperbolic sine.
4 5 6 asin - Inverse sine.
7 8 9 asinh - Inverse hyperbolic sine.
cos - Cosine.
We can recall what variables we have put into MATLAB by typing ‘who’ or ‘whos’: cosh - Hyperbolic cosine.
acos - Inverse cosine.
>> B = 3; acosh - Inverse hyperbolic cosine.
>> A = [1 2 3; 4 5 6; 7 8 9]; tan - Tangent.
>> who tanh - Hyperbolic tangent.
atan - Inverse tangent.
Your variables are: atan2 - Four quadrant inverse tangent.
atanh - Inverse hyperbolic tangent.
A B sec - Secant.
sech - Hyperbolic secant.
>> whos asec - Inverse secant.
Name Size Bytes Class asech - Inverse hyperbolic secant.
csc - Cosecant.
A 3x3 72 double array csch - Hyperbolic cosecant.
B 1x1 8 double array acsc - Inverse cosecant.
acsch - Inverse hyperbolic cosecant.
Grand total is 10 elements using 80 bytes cot - Cotangent.
coth - Hyperbolic cotangent.
MATLAB can also deal with complex numbers. It is convenient to assign a variable acot - Inverse cotangent.
name, usually as i or j, to the square root of –1, acoth - Inverse hyperbolic cotangent.
>> i = sqrt(-1)
Exponential
i= exp - Exponential.
log - Natural logarithm.
0 + 1.0000i log10 - Common (base 10) logarithm.
log2 - Base 2 logarithm and dissect floating point number.
>> x = 3 + 2i pow2 - Base 2 power and scale floating point number.
sqrt - Square root.
x=
3.0000 + 2.0000i Complex
abs - Absolute value.
2.4 Use of built-in functions angle - Phase angle.
conj - Complex conjugate.
MATLAB provides a large number of standard elementary mathematical functions, imag - Complex imaginary part.
including abs, sqrt, exp, etc. It also offers many advanced mathematical functions, real - Complex real part.
such as the Bessel and gamma functions. Most of these functions accept complex unwrap - Unwrap phase angle.
arguments. isreal - True for real array.
11 12
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
cplxpair - Sort numbers into complex conjugate pairs.
Note that these functions will operate directly on vector and matrix quantities, as well
as a scalar value. For example:
>> B = 100;
>> sqrt(B)
ans =
10
>> A = [4 9 16 25 36];
>> Sqrt(A)
??? Undefined command/function 'Sqrt'.
>> sqrt(A)
ans =
2 3 4 5 6
• You can always ask for MATLAB assistance when you are not sure of the
commands. Type ‘help command’ or ‘lookfor command’. For example:
>> help ones
ONES Ones array.
ONES(N) is an N-by-N matrix of ones. Figure 2.1
ONES(M,N) or ONES([M,N]) is an M-by-N matrix of ones.
ONES(M,N,P,...) or ONES([M N P ...]) is an M-by-N-by-P-by-... array of
ones.
ONES(SIZE(A)) is the same size as A and all ones.
……………
>> lookfor ones
ONES Ones array.
SPONES Replace nonzero sparse matrix elements with ones.
SLUPDATE Replace blocks from a previous release with newer ones.
DRAMADAH Matrix of zeros and ones with large determinant or inverse.
• Having learned how to assign values to variables, we can then see how
MATLAB performs mathematical operations on these variables 
HANDOUT 3
13 14
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
Figure 2.2
Figure 2.4
Figure 2.3
15 16
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
Handout 3 : Introduction to MATLAB
MATLAB fundamentals
3.1 Matrix and array operations
3.1 Matrix and array operations Array operations
3.2 Plotting in MATLAB The following examples demonstrate how array operations are carried out in
MATLAB:
3.3 Other resources
• Colon notation
>> x = 0:2
x=
0 1 2
>> x = 0:0.1:1
x=
Columns 1 through 5
0 0.1000 0.2000 0.3000 0.4000
Columns 6 through 10
0.5000 0.6000 0.7000 0.8000 0.9000
Column 11
1.0000
• Using array with functions
>> x = 0:0.1*pi:pi
x=
Columns 1 through 5
0 0.3142 0.6283 0.9425 1.2566
Columns 6 through 10
1.5708 1.8850 2.1991 2.5133 2.8274
17 18
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
Column 11 >> D = A.*B
D=
3.1416 1 6 15 28 45
>> y = sin(x) >> D = A./B
D=
y= 1.0000 0.6667 0.6000 0.5714 0.5556
Columns 1 through 5 >> A.^2
ans =
0 0.3090 0.5878 0.8090 0.9511 1 4 9 16 25
Columns 6 through 10 Arrays involving complex numbers
1.0000 0.9511 0.8090 0.5878 0.3090 >> a = [1 2 3 4 5];
>> b = a + a*j
Column 11
b=
0.0000
Columns 1 through 3
• Addressing array contents
1.0000 + 1.0000i 2.0000 + 2.0000i 3.0000 + 3.0000i
>> x(3)
Columns 4 through 5
ans =
4.0000 + 4.0000i 5.0000 + 5.0000i
0.6283
>> c = b'
>> y(1:5)
c=
ans =
1.0000 - 1.0000i
0 0.3090 0.5878 0.8090 0.9511 2.0000 - 2.0000i
3.0000 - 3.0000i
4.0000 - 4.0000i
5.0000 - 5.0000i
>> K = x(3:-1:1)
>> c = b.'
K=
c=
0.6283 0.3142 0
1.0000 + 1.0000i
• Array mathematics 2.0000 + 2.0000i
3.0000 + 3.0000i
>>A = [1 2 3 4 5]; 4.0000 + 4.0000i
>>B = [1 3 5 7 9]; 5.0000 + 5.0000i
>> A + B
ans =
2 5 8 11 14
19 20
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
Matrix operations and manipulations
1
>> A = [1 2 3; 4 5 6; 7 8 9] 4
2
A= 5
3
1 2 3 6
4 5 6
7 8 9 >> A(:,3) = []
>> A(2,1) A=
ans = 1 2 0 0 0
4 5 0 0 0
4 7 8 0 0 0
>> A(2,3) >> sum(A)
ans = ans =
6 12 15 0 0 0
>> A(3,3) = 0 >> Adash = A'
Adash =
A=
1 4 7
1 2 3 2 5 8
4 5 6 0 0 0
7 8 0 0 0 0
0 0 0
>> A(2,6) = 0 >> sum(Adash)
A= ans =
1 2 3 0 0 0 3 9 15
4 5 6 0 0 0
7 8 0 0 0 0 Some useful commands for matrices operations
>> B = A(1:2,1:3) zeros - Zeros array.
ones - Ones array.
B= eye - Identity matrix.
rand - Uniformly distributed random numbers.
1 2 3 randn - Normally distributed random numbers.
4 5 6 linspace - Linearly spaced vector.
logspace - Logarithmically spaced vector.
>> C = B(:)
size - Size of matrix.
C= length - Length of vector.
21 22
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
ndims - Number of dimensions. 4
disp - Display matrix or text.
isempty - True for empty matrix. >> A= ones(2,2)
isequal - True if arrays are identical.
isnumeric - True for numeric arrays. A=
islogical - True for logical array.
logical - Convert numeric values to logical. 1 1
reshape - Change size. 1 1
diag - Diagonal matrices and diagonals of matrix.
tril - Extract lower triangular part. >> B = [A+1 A+2 A+3]
triu - Extract upper triangular part.
fliplr - Flip matrix in left/right direction. B=
flipud - Flip matrix in up/down direction.
2 2 3 3 4 4
flipdim - Flip matrix along specified dimension. 2 2 3 3 4 4
rot90 - Rotate matrix 90 degrees.
: - Regularly spaced vector and index into matrix. 3.2 Plotting in MATLAB
find - Find indices of nonzero elements.
end - Last index.
In this handout we will only look at the basic plotting facilities offered by MATLAB.
We will look at some examples on how to create basic 2D graphs.
More examples:
>> x = 0:0.1*pi:2*pi;
>> A = [1 2 3; 4 5 6; 7 8 9]
>> y = sin(x);
>> plot(x,y)
A=
>> xlabel('x')
>> ylabel('sin(x)')
1 2 3
>> title('A sample graph')
4 5 6
7 8 9
The graph is shown in Figure 3.1. MATLAB also allows the user to change the
properties of a graph using the mouse, through its GUI. Refer to the description in
>> size(A)
Figure 3.1.
ans =
3 3
>> F = 5*ones(3,3)
F=
5 5 5
5 5 5
5 5 5
>> G = diag(F) - 1
G=
4
4
23 24
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
Figure
To plot more than one set of data in one graph (See figure3.1
3.2):
>> y2 = sin(x-0.25);
>> y3 = sin(x-0.5);
>> plot(x,y,x,y2,x,y3)
>> legend('y', 'y2', 'y3')
More on line styles and colours
The standard syntax is
Plot(x, y, ‘colourlinemarker ’), where colourlinemarker is:
• Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k', corresponding to cyan,
magenta, yellow, red, green, blue, white, and black respectively.
• Line style strings are '-' for solid, '--' for dashed, ':' for dotted, and '-.' for dash- Figure 3.2
dot. You can omit the line style command if you want.
• The marker types are '+', 'o', '*', and 'x' and the filled marker types 's' for
square, 'd' for diamond, '^' for up triangle, 'v' for down triangle, '>' for right
triangle, '<' for left triangle, 'p' for pentagram, 'h' for hexagram.
For example,
>> plot(x,y,'ko') – See figure 3.3
>> plot(x,y,'--ko') – See figure 3.4
3.3 Other resources
MATLAB comes with plenty of other useful tools. You can browse their website,
www.mathworks.com, to find more about MATLAB capabilities. We will also learn
about more advanced MATLAB commands/toolboxes as we go along this course.
In the next handout, we will see how MATLAB can be utilized to solve engineering
problems  Handout 4: MATLAB programming
Figure 3.3
25 26
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
Handout 4 : Introduction to MATLAB
Programming with MATLAB
4.1 Input & Output
4.2 Structured programming & Flow control
Figure 3.4
27 28
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
>> x = 0:0.2:1;
>> y = sin (x');
4.1 Input & Output >> disp([x' y])
0 0
0.2000 0.1987
This section will demonstrate the input and output statements in MATLAB. As well
0.4000 0.3894
as using direct input and output from the user, we will also see how MATLAB deals
0.6000 0.5646
with data from/to external files.
0.8000 0.7174
1.0000 0.8415
Prompting for user input >> format short
>> disp (pi)
By default, the input function returns a numerical value. If you want a string input, a 3.1416
second parameter ‘s’ must be provided. See examples below.
>> format long
>> disp(pi)
Text Output to Screen 3.14159265358979
>> format short e
There are two functions for text output; namely disp and fprintf. The latter allows you
>> disp(pi)
more control over the displayed information (more details on fprintf later). The
3.1416e+000
function disp, on the other hand, takes only one argument, which can be a string or
numerical value (see examples below).
Working with external data files
In addition to disp and fprintf, the format command controls the display of numerical
values in the command window.
Examples with input, disp and format : Let see the save and load command.
>> NomborID = input ('Enter your user ID number')
Enter your user ID number 3 >> x = 4;
>> y = 4;
NomborID = >> z = x+y;
>> save xyztest
3 >> load xyztest
>> who
>> Nama = input ('Enter your name', 's')
Enter your name AHMAD Your variables are:
Nama = x y z
AHMAD >> x
>> disp ('I am a student') x=
I am a student
>> disp (['Nama saya ialah', Nama]) 4.00
Nama saya ialah AHMAD
>> disp (['My ID number is ', num2str(NomborID)]) >> whos
My ID number is 3 Name Size Bytes Class
29 30
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
x 1x1 8 double array sqrt(2) 1.4142 1.414e+00
y 1x1 8 double array
z 1x1 8 double array
4.2 Structured programming & Flow control
Grand total is 3 elements using 24 bytes
MATLAB has several commands that enable the user to control the flow of their
> >x = 3;
>> y = 2; program. We will see the following five basic commands for flow control.
>> z = 5;
>> save xyztxt.txt –ascii • for loops
• if loops
More commands  See the fopen, fscanf, fgetl and fclose command (to be discussed • while loops
in lectures) • switch loops
• break statements
The fprintf function
For-end loops
There are three ways in which this function can be used. This is best demonstrated The for loop repeats a group of statements prescribed number of times. The syntax is
through examples. best described through some examples:
>> fprintf('Hello, My name is Norshah') >> for i = 1:3 >> for n = 1:2:5
Hello, My name is Norshah>> disp(i) disp(n)
>> fprintf('Hello, My name is Norshah\n') end end
Hello, My name is Norshah 1.00 1.00
>>
2.00 3.00
>> name = 'Norshah';
>> age = 50; 3.00 5.00
> fprintf('%s is a %d year old man\n', name, age) >> >>
Norshah is a 50 year old man >> for n = 1:5 >> for n = 1:5
A(n) = n + 10; fprintf('The position number %d is %d\n',n, n)
>> x = 2;y =3; z = 4; disp(A(n)) end
>> idfile = fopen('OK.txt', 'wt'); end
>> fprintf(idfile,'%d %d %d' , x, y, z); The position number 1 is 1
>> fclose(idfile); 11.00 The position number 2 is 2
>> 12.00 The position number 3 is 3
13.00 The position number 4 is 4
Formatting codes are listed in the tables below: 14.00 The position number 5 is 5
15.00 >>
%s Format as a string >>
%d As Integer part
%f As floating point value An important concept is the NESTED LOOP  Basically means ‘ A Loop in
%e Floating point in scientific notation another loop’. Usually the most common application is when you are dealing
%n Insert new line with matrices. As usual – some examples follow!
>> for i = 1:3 Notice the indentation of the
For examples: for j = 1:4 statements. In programming, you
A(i,j) = i + j; do this to make your programs
Value %8.4f %12.3e end easier to check and so that you can
2 2.0000 2.000e+00 end easily see various nested loops.
>> A
31 32
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223) : PART I
A= *Note: Relational operators in MATLAB.
2.00 3.00 4.00 5.00 < Is less than
3.00 4.00 5.00 6.00 <= Is less than or equal to
4.00 5.00 6.00 7.00 > Is greater than
>= Is greater than or equal to
>> == Is equal to
~= Is not equal to
If-end Statement
The if statement evaluates a logical expression and executes a group of statements While-end loop
when the expression is true. The optional elseif and else keywords also enable
execution of alternative statements. An end keyword terminates the last group of The while statement execute a group of statements repetitively under
statements. control of a logical condition. For examples:
The general form of the IF statement is
>> i = 1;
IF expression >> while i < 10
statements disp(i)
ELSEIF expression i = i+3;
statements end
ELSE 1.00
statements
END 4.00
7.00
Some examples:
>>
>> A = 5; >> for i = 1:3
>> B = 10; for j = 1:3
>> if A < B if (i==j) Switch-end loop
disp(A) disp(A(i,j))
else end The switch structure is an alternative to a long sequence of elseif blocks in an if-end
disp(B) end loop. The syntax can be understood using the following examples:
end end
>> x = 5;
5.00 1.00 >> switch sign(x)
>> 5.00 case -1
9.00 disp('x is negative');
>> case 0
disp('x is zero');
case 1
disp('x is positive');
otherwise
disp('test fails')
end
x is positive
33
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
>> Handout 5 : Introduction to MATLAB
Break statement
This command (analogous to GOTO function in various older computer codes) is M-files & Samples of MATLAB applications
used as an escape mechanism from a while-end loop (usually in ITERATIONS
PROCEDURE). For example:, in the following loop:
5.1 M-files : script m-file & function m-file
Iter = 0;  Iteration counter 5.2 Analysis of sample MATLAB programs
Maxit =  Set the number of iterations
Tolerance = …  Set the tolerance
xold = ….  Initial value
x = ……  Initial value
while Iter < Maxit
xold = x;  Save for convergence check
x = …..  Do operation on x
Iter = Iter + 1;
If abs ((x-xold)/xold) < Tolerance
break;
Test for convergence. If this
end
condition is met, the break
end
statement will bring you out of
the while-end loop – and go to
the next statement.
35 36
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
6.0240e+023
5.1 M-files
>> Rgas
So far, you have learnt how to enter commands and values in MATLAB; assign
Rgas =
variables/vectors/matrices, carry out mathematical operations on them and plot the
results. You have also learnt how to apply MATLAB commands to control your
8315
program.
>>
Notice that in previous handouts, we ask MATLAB to do operations for us by simply
typing the commands into the MATLAB screen via the command prompt >>, let
MATLAB do its job and give us the answer. That is basically trivial if you have only Function m-files
single applications that you want MATLAB to run at one time. But what if you want
MATLAB to carry out lots of functions consecutively? In that case, you must utilize
the M-files. Basically an m-file is just a collection of commands that you store in a These are more useful than script m-files in the sense that they allow you to
plain text file with an extension *.m. You can have script m-files and function m- communicate with the command window and other functions via a predefined list of
files. M-files can be executed by typing their names at the command prompt. input and output parameters. As you shall see, function m-files are the backbone of
MATLAB programming.
Script m-files
Similarly, you can create a function m-file by clicking FileNew m-File in
Script m-files have no input or output parameters. They are useful when you want to
MATLAB.
store some constant parameters that you want to use for many times in your program.
For example, lets create a file to store some constants. To create an M-file, in
The first line of a function m-file has the form,
MATLAB, click File New m-file. Type the constants as below, and save the file
as myconstant.m for example.
function [outputparameterlist] = functionname [ inputparameterlist]
% A script m file to store constants that I will use where outputparameterlist and inputparameterlist are comma-separated list of
% later in my program variables used to pass data into and out of the function. Let’s see examples showing
different usage of these input and output parameters.
gravity = 9.81; % gravity acceleration, m/s2
avagadro = 6.024e23; % number of molecules in a mole % to compute sum of two values
Rgas = 8315; % Universal gas constant J/kmol/K function a = twosum(x,y) twosum.m
a = x+y;
To run the file, type:
>> m = 3; n = 2;
>> twosum(m,n)
>> myconstant
>> gravity
ans =
gravity =
5
9.8100
>> twosum(2,3)
>> avagadro
ans =
avagadro =
5
37 38
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
>> twosum2(1,3)
>> k = [ 1 2 3];
>> l = [ 1 2 3]; ans =
>> twosum(k,l)
4
ans =
>> [g h] = twosum2(1, 3)
2 4 6
g=
>>
4
% to compute sum of two values and show
% the property of local variables showlocal.m
function a = showlocal(x,y) h=
disp(x); disp(y);
a = x+y; 8
>>
>> x = 4; y = 5;
>> showlocal(1,2)
1 Note: There are other commonly used MATLAB commands to evaluate function
values  eval and inline. See examples below:
2
>> x = [1 2 3 4 5];
ans = >> fx = 1 + x.^2;
>> eval ('fx',x)
3
Demonstrating the important concept of fx =
>> x LOCAL variables
2 5 10 17 26
x=
>> functionbaru = inline ('sin(x)*cos(x)')
4
functionbaru =
>> y
Inline function:
y= functionbaru(x) = sin(x)*cos(x)
5 >> x = 1.4;
>> functionbaru(x)
>>
ans =
% showing two output parameters 0.1675
function [a b] = twosum2(x,y)
a = x+y; twosum2.m >> sin(x)*cos(x)
b = 2*x+2*y; ans =
0.1675
39 40
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
Handout 6 : Errors in Numerical Methods
CHAPTER 3 : Approximations and Round-off
Errors
CHAPTER 3 : Approximations and
Round-off Errors
From the example of the falling parachutist, it was seen that
numerical methods are not always accurate. However, where
3.3 Error Definitions numerical solutions are needed, we should be aware of the
magnitude of the errors.
Three main type of errors:
1. round-off errors – inaccurate number representation
2. truncation errors – use approximations in formulas
3. human errors – blunders, formulation or model errors and
uncertainty
CHAPTER 4 : Truncation errors and
the Taylor series
3.3 Error Definitions
True error,
E t = true value-approximation
4.1 The Taylor Series
To quantify the magnitude, this equation can be normalized. The
4.2 Error propagation true percent relative error,
true error
εt = 100%
true value
4.3 Total numerical error
However in real-world applications, we will obviously not
know the true answer a priori. Thus alternatively, the best
approximations can be used,
approximat e error
εa = 100%
approximat ion
Certain numerical methods use an iterative approach to compute
answers. Thus, the percent relative error,
41 42
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
CHAPTER 4 : Truncation errors and the
current approximation − previous approximation Taylor series
εa = 100%
current approximation
Truncation errors – due to the use of approximate
mathematical procedures in place of exact ones. For example,
Often, when performing computations, we are interested in in the case of falling parachutist problem, we used the
whether the percent absolute value is lower than the prespecified approximation:
percent tolerance, ε s
εa < εs dv ∆v v ( t ) − v ( ti )
≅ = i +1
dt ∆t ti +1 − ti
It is also convenient to relate these errors to the number of
signicant figures in the approximation. It can be shown
and this led to error in the final result. To understand how this
(Scarborough, 1966) that if the following criterion is met, the
occured, we turn to mathematical formulation that is used
result is correct to at least n significant figures
widely to express functions in an approximate fashion –
‘Taylor Series’
ε s = (0.5 × 10 2 − n )%
Example 3.2 pg 56
4.1 The Taylor Series
Any smooth function can be approximated as a polynomial.
Taylor series provides a means to predict the value of a function
at one point in terms of the function value and its derivatives at
another point.
• f ( xi +1 ) ≅ f ( xi ) - zero order approximation, only
true if xi +1 and xi are very close to each other.
• f ( xi +1 ) ≅ f ( xi ) + f ′( xi ) ( xi +1 − xi ) - first order
approximation, in form of a straight line
• n-th order
43 f ′′ f ( n ) 44n
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
f ( x i Dr. ≅ Salleh,
+ 1 )Hanim f ( x iMechanical x i ) h + UNITENh©22007/2008
) + f ′ (Department, +K + h + Rn
2! n!
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
f ( n +1)ξ ?
where h = xi +1 − xi Rn = h n +1
( n + 1)
n=3, second order approximation:
f ( n +1) (ξ ) ( n +1)
Rn = h
(n + 1)!
?
n=4, second order approximation:
?
Example 4.1
Summary:
Use 0 to 4th order Taylor series expansions to approximate the
function: • If we take only the first term of the series, and neglect all
other terms, then it is called as 'zero order expansion. The
f ( x) = −0.1x 4 − 0.15 x 3 − 0.5 x 2 − 0.25 x + 1.2
function is now taken as a constant since f(xi+1)=f(xi).
from xi = 0 with h = 1 (i.e. predict its value at xi +1 = 1 ). • If we take the first two terms, then it is first order
expansion. This is what we used in the parachutist
True value, f (1) = 0.2 problem.
Solution: • Usually, adding more terms to the series will only improve
the series marginally.
for n=0, zero order Taylor Series approximation gives
f ( xi +1 ) 1.2 • At some point, the improvement becomes insignificant and
then we can stop adding terms. If the function we are
at x = 1 , truncation error, Et = 1.2 − 0.2 = −1.0 dealing with is a polynomial, then the Taylor series will
n=1, first order approximation: have finite number of terms but for most of the functions,
we have an infinite series. When we chop off the series
calc - f ′(0) = −0.25 , thus f ( xi +1 ) 1.2 − 0.25h, f (1) = 0.95 after a few terms, then we have a 'truncation error’
A Dilemma: The error is given by the remainder term Rn.
Et = 0.2-0.95 = -0.75
However, the term ξ is not known, hence we cannot get the
n=2, second order approximation: correct value of Rn. Also we should know all the n+1
derivatives of f(n), which means, we should know f(n). If we
45 46
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
know f(n), then, there is no need to perform the Taylor Series Given a function f ( x ) . Assume that x% is an approximation of
analysis. But, we still use the series and get the important x . We would like to estimate the discrepancy
message that
Rn=O(hn+1) ∆f ( x% ) = f ( x ) − f ( x% )
O(hn+1) means "of the order of hn+1 i.e. the error is of the order
of hn+1. If h is very small, then error is also very small. It also but since x is unknown f ( x ) is unknown. Thus if x% ≈ x can
shows that if : use Taylor series,
- error is O(h) halving the h will halve the error. f ′′ ( x% ) 2
f ( x ) = f ( x% ) + f ′ ( x% )( x − x% ) + ( x − x% ) + ..
- error is O(h2) halving the h will quarter the error. 2
drop 2nd order and higher term, and rearrange
This is a very useful information for numerical analysis.
f ( x ) − f ( x% ) ≅ f ′ ( x% )( x − x% ) or
∆f ( x% ) ≅ f ′ ( x% )( x − x% ) eqn (4.25)
See example 4.3 for the effect of
nonlinearity and step size on the Taylor Figure 4.7
Series approximation.
4.2 Error Propagation
Purpose is to study how errors in number
propagates through mathematical
functions. E.g. multiply two numbers that 4.2.2 Functions of more than one variable
have errors, would like to estimate the If a function of two independent variables u and v , the Taylor
error in the product. series becomes
∂f ∂f
f ( ui+1 , vi +1 ) = f ( ui , vi ) + ( ui+1 − ui ) + ( vi+1 − vi ) + ..
∂u ∂v
1  ∂2 f 2 ∂2 f ∂2 f 2
4.2.1 Functions of a single variable
 ( ui+1 − ui ) + 2 ( ui+1 − ui )( vi+1 − vi ) + 2 ( vi+1 − vi )  + ..
2!  ∂u 2 ∂u∂v ∂v 
47 48
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I Numerical methods for engineers (COEB223): PART I
where all partial derivatives are evaluated at the base point i.
Dropped higher order terms, rearranged
∂f ∂f
∆f ( u% , v% ) = ∆u% + ∆v%
∂u ∂v
for n independent variables,
∂f ∂f ∂f
∆f ( x%1 , x%2 ,..x%n ) ≅ ∆x%1 + ∆x%2 + .. + ∆x%n eqn (4.27)
∂x1 ∂x2 ∂xn
Example 4.6 Error propagation in a multivariable function
4.3 Total numerical error
- summation of truncation and round-off errors
- to minimize round-off errors - increase the number of
significant figures of the computers
- to decrease truncation error – decrease step size ; but
increase computations and increase round-off errors
49 50
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008 Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008
Numerical methods for engineers (COEB223): PART I
Dilemma: decrease the step size to decrease truncation error
but at the same time increase round-off errors!
51
Dr. Hanim Salleh, Mechanical Department, UNITEN © 2007/2008

S-ar putea să vă placă și