Sei sulla pagina 1di 83

Kathmandu University

School of Science
Department of Mathematics

Lecture Notes

SCIENTIFIC COMPUTING WITH


MATLAB
Dr. Nicole Marheineke
TECHNISCHE UNIVERSITT
KAISERSLAUTERN
Fachbereich Mathematik
Arbeitsgruppe Technomathematik

Winter Semester 2005

Course Overview

Course Title:
Scientific Computing with MATLAB (Numerical Computation)
64 h computer class
Course Description:
This course introduces the main ideas and concepts of scientific computing. It is particularly split into two parts, a theoretical and a practical one. In the theoretical part,
mathematical methods and algorithms concerning numerical analysis are presented
that are then implemented by the students in the practical part. For the implementation, the software tool MATLAB is used.
Course Objectives:
The main objectives of this course are to enable the students:
to broaden their mathematical knowledge towards numerical methods and algorithms
to learn programming
to apply MATLAB for solving mathematical problems numerically and visualizing their simulation results graphically
Course Topics:
Introduction into MATLAB
Statistical evaluation of data
Curve fitting routines
Interpolation, approximation, numerical integration
Solving of linear and non-linear systems
One-step methods for (non-)stiff ODEs
Finite difference methods for PDEs
MonteCarlo simulations

Literature:
[1] K. Sigmon: MATLAB Primer, 3rd ed, University of Florida, Department of Mathematics, 1993 (print-out provided)
[2] MATLAB Quick Reference (print-out provided)
[3] MATLAB Help Desk (on-line help, installed in MATLAB)
Further documentations, practical introductions, guides and tutorials for MATLAB can be downloaded for free from the internet:
> go on the webpage http://www.yahoo.com or http://www.google.com
> search for MATLAB
[4] N. Marheineke: Lecture notes Numerics for differential equations, Kathmandu
University, Department of Mathematics, 2005
[5] J. Stoer and R. Bulirsch: Introduction to numerical analysis, Springer, 2002

CONTENTS

Contents
1 What is Scientific Computing?

2 Introduction into MATLAB

2.1 What is MATLAB? . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.2 Accessing MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2.3 Scalar Operations and Build-in Functions . . . . . . . . . . . . . . . . .

2.4 Entering Vectors and Matrices . . . . . . . . . . . . . . . . . . . . . . .

2.5 Variables, Expressions, Statements and Saving a Session . . . . . . . .

2.6 Vector/Matrix Operations and Build-in Functions . . . . . . . . . . . .

2.7 Control Structures and Logical Operators . . . . . . . . . . . . . . . . .

10

2.8 M-Files: Script and Function Files

. . . . . . . . . . . . . . . . . . . .

12

2.9 Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

13

2.10 Further Useful Commands . . . . . . . . . . . . . . . . . . . . . . . . .

14

3 Exercises

15

3.1 MATLAB as Interactive Calculator . . . . . . . . . . . . . . . . . . . .

15

3.2 M-Files in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . .

16

? Statistical Evaluation of Data . . . . . . . . . . . . . . . . . . . . . .

16

3.3 If, For, While, Text Output and Editing Graphics . . . . . . . . . . . .

17

? ODE: Stability and Explicit Euler Method . . . . . . . . . . . . . . .

17

? ODE: Importance of Step Size in Explicit One-Step Methods . . . .

20

? ODE: Convergence Order


Explicit Euler vs Explicit Classical RungeKutta Method . . .

20

? Algorithmic Programming: Sorting and Searching Routine . . . . . .

21

3.4 ODE-Solvers and Efficiency of Algorithms . . . . . . . . . . . . . . . .

22

? ODE: Implicit One-Step Methods, Newton Method . . . . . . . . . .

22

3.5 Matrix Manipulations, Sparse Matrices and 3D-Plots . . . . . . . . . .

23

? PDE: Finite Differences . . . . . . . . . . . . . . . . . . . . . . . . .

23

3.6 Nargin, Switch, Polynomial Functions and M-File Management . . . . .

25

? MonteCarlo Simulation . . . . . . . . . . . . . . . . . . . . . . . . .

25

? Numerical Integration . . . . . . . . . . . . . . . . . . . . . . . . . .

26

? Curve Fitting Routines . . . . . . . . . . . . . . . . . . . . . . . . .

28

Contents
4 Possible Implementations and Further Comments

29

4.1 MATLAB as Interactive Calculator . . . . . . . . . . . . . . . . . . . .

29

4.2 M-Files in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29

? statistics.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30

4.3 If, For, While, Text Output and Editing Graphics . . . . . . . . . . . .

32

? stability.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

32

? step size.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

38

? euler vs rk.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

43

? search.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

48

4.4 ODE-Solvers and Efficiency of Algorithms . . . . . . . . . . . . . . . .

51

? implicit.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

51

4.5 Matrix Manipulations, Sparse Matrices and 3D-Plots . . . . . . . . . .

57

? fd.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

57

4.6 Nargin, Switch, Polynomial Functions and M-File Management . . . . .

64

? random walk.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

64

? integration.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

67

? fitting.m . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

72

5 Test Questions and Answers

76

1. What is Scientific Computing?

What is Scientific Computing?

Real-life problems in science, engineering and technology can be in general described


by a mathematical model. This might be for example a set of differential equations, an
optimization or control problem and/or a statistical data analysis. Mostly, the arising
mathematical models are highly complicated and too complex to be solved analytically.
Hence, appropriate numerical methods must be applied to provide approximative solutions with help of the computer. The procedure of deriving numerical algorithms,
implementing them in a programming language and interpreting their results is known
as Scientific Computing.
This course Scientific Computing with MATLAB focuses on the treatment of ordinary and partial differential equations as well as statistical and stochastical problems
by using the software tool MATLAB.
Actually, scientific computing is not theoretically teachable but only practically learnable, since programming mainly depends on the individual way of dealing with problems, thinking and structuring facts in a logical order as well as on personal preferences
and experiences. Thus, two programs written by two independent persons for the same
mathematical algorithm will always differ. There is no unique solution for a programming task. Instead, the quality of a program is measured in terms of computation
time and number of operations. These independent parameters are strongly affected
by the used soft- and hardware due to the required data storage. Therefore, a program
running fast and efficiently in FORTRAN might be very slow in C.

Learning by Doing
is the motto of the course which is also reflected in the structure of these lecture notes.
After a short introduction into MATLAB in Ch 2 that is meant as survey of the powerful possibilities and build-in functions and undoubtedly far away from completeness,
the exercise tasks with helpful hints and MATLAB commands in Ch 3 are designed
to appeal for a constructive self-study in programming. In Ch 4 possible implementations and further extensions for advanced programmers are presented. Moreover, the
simulation results are visualized and mathematically discussed.
The development of an individual good programming style requires a lot of practice.
Hence, it is reasonable to implement further one-step methods, finite differences and
element methods [4] as well as curve fitting, interpolation or integration routines [5] in
addition to the limited number of given examples. Apart from differential equations,
statistics and stochastics, MATLAB can certainly be applied for handling optimization
and control problems as well as all other imaginable mathematical algorithms.

Have fun in discovering the scope and power of


MATLAB.

2. Introduction into MATLAB

rag replacements 2

Introduction into MATLAB

2.1

What is MATLAB?

MATLAB (MATrix LABoratory) is an interactive, matrix-based system for scientific


and engineering numerical computation and visualization. It is a powerful tool that
might solve complex numerical problems in a fraction of time required by other programming languages such as FORTRAN or C.

easily linked
Other
Software

read in/
read out
files

Programming
&
Visualization
Tool

Mathematical
Library

commercial tools
C-program
data files

to develop own
software

calculation
operations

build-in
functions

to evaluate date

control
structures

tool boxes
(can be bought
and added)

to visualize data
m-files
Calculator

interactive

Figure 2.1: Software tool MATLAB

2.2

Accessing MATLAB

Start:
1. access MATLAB from the menu or click the MATLAB icon on the desktop
2. MATLAB command shell pops up
3. all further commands in this shell are interpreted as MATLAB commands
Quit:
type quit or exit in the control line
quit resp. exit closes all open figures (plot windows)

2. Introduction into MATLAB


quit resp. exit deletes all unsaved data
Delete:
single letters are deleted by BACKSPACE
old commands are recalled by the cursors

Help:
type help or help a particular topic in the command line
alternatively, use the on-line help in the menu and click on helpdesk

2.3

Scalar Operations and Build-in Functions

MATLAB knows real and complex numbers, i.e. 1, 2.5, 4.6+6i . When listing a

number in exponential form, e.g. 2.79 1010 = 2.79e-10, blank spaces must be
avoided.
Operations:

+ addition
- subtraction
* multiplication

power
\ left division
/ right division

Build-in functions:

abs()
real()
round()
exp()
sin()
tan()

= Note that for scalars the left and the right


division yield the same result!
absolute value,
real part,
rounded integer value,
exponential function,
sine,
tangent,

sqrt()
imag()
sign()
log()
cos()
gamma()

square root
imaginary part
signum function
logarithm
cosine
gamma function

The name of all build-in MATLAB functions starts with a small letter. The arguments
of the functions are stated in round brackets (.), consider for example the following
command line
>> real(4+i)
>> ans = 4

2.4

Entering Vectors and Matrices

MATLAB works with only one object, namely a rectangular numerical matrix with
possibly complex numbers or characters (text strings) as entries. Hence, scalars are
represented by a ( 1 1 )-matrices and vectors (row resp. column vectors) by ( 1 n )
resp. ( n 1 )-matrices, n N .
Matrices can be introduced into MATLAB in several ways:
given by explicit lists of elements
generated by build-in statements and functions
created in diskfiles

2. Introduction into MATLAB


loaded from external data files
Entering matrices by a list of elements is exemplified in the following.
Row vector: a = (1 4.6 27+5i 6 105)
>> a = [1,4.6,27+5i,6e5] or alternatively

1
4.6

Column vector: b =
27+5i
6 105
>> b = [1;4.6;27+5i;6e5] or alternatively

>> a = [1 4.6 27+5i 6e5]

>> b = [

1
4.6
27+5i
6e5

ENTER
ENTER
ENTER
]


1 2 3
Matrix: A =
4 5 6
>> A = [1,2,3;4,5,6]
or alternatively >> A = [1 2 3;4 5 6]
or
>> A = [ 1 2 3 ENTER
>> A = [ 1, 2, 3 ENTER
or
4, 5, 6
]
4 5 6
]
The elements of matrices are stated in square brackets [.]. Thereby, the components
in a row are separated by comma or blank, the ones in a column by semicolon or new
line.
The following input creates also a matrix, in particular a row vector
>> [-2:1 4:-2:1 27.3 8:0.5:9]
>> ans = -2 -1 0 1 4 2 27.3 8 8.5 9
The syntax reads [start value : increment : end value]. If the increment is missing, it is 1 by default.

2.5

Variables, Expressions, Statements and Saving a Session

MATLAB is an expression language. The expressions being typed are interpreted and
evaluated. MATLAB statements are usually of the form
variable = expression or simply expression
Expressions are usually composed from operators, functions and variable names. Evaluating an expression produces a matrix that is displayed on the screen and assigned
to the variable for future use. Hence, all variables represent matrices. The name of a
variable has at least 1 character and at most 19. It might contain digits, but no operation signs and the first character is always a letter, a, A, b, B, c, C etc. MATLAB
distinguishes between capital and small letters, e.g. E1 12 is not the same as e1 12.
A variable is defined by means of the equality sign, e.g.
>> A1 = 4
>> A2 = [1:2:10]
>> a1 = This is a text string.

2. Introduction into MATLAB

If the variable name and the equality sign are omitted, the variable ans (for answer)
is automatically created to that the result is assigned, e.g.
input: >> 2+2 ENTER
= output: >> ans = 4
MATLAB possesses a number of already defined variables: eps, realmax, pi, i,
j, inf, NaN, nargin, nargout. The command who or whos lists the variables currently in the workspace except from the permanent ones. A variable can be deleted
from the workspace with the command clear variable name. The command clear
alone clears all non-permanent variables.
MATLAB states the result after each statement, e.g.
input: >> a = 2+2 ENTER
= output: >> a = 4
input: >> 2+2 ENTER
= output: >> ans = 4
The output is suppressed, but the assignment is carried out, if the last character of
the statement is a semicolon. The use of the semicolon is essential in avoiding the
unwanted printing of intermediate results, cf.
input >> a = 2+2; ENTER
= no output
A statement is normally terminated in a single line with ENTER .
can be continued to the next line with three or more dots, ...,
>> a+b+c+... ENTER
+d+e;
On the other hand, several statement can be placed on a single
commas or semicolons,
input: >> x = 1, y = 2; z = 3 ENTER
= output: >>

However, a statement
followed by ENTER ,

line if separated with


x = 1

>> z = 3

The command format changes the representation of the numbers, format short,
format long etc.
When logging out or exiting MATLAB all variables are lost. Invoking the command
save before exiting causes all variables to be written to a non-human-readable diskfile
named matlab.mat. When restarting MATLAB, the command load restores the
workspace to its former state.
Save:
load: variables are read in
save: variables are read out

2.6

Vector/Matrix Operations and Build-in Functions

Operations:
The array operations are the same as the scalar operations: +, -, *, , \ , /. And
additionally, represents the conjugate, transpose. The matrix-matrix operations
resp. matrix-vector operations obey the rules of linear algebra. If the sizes of the
objects are incompatible for the operation, an error message is produced on the screen.
Note that in case of matrix-scalar operations (for addition, subtraction, multiplication
and division) the scalar operates componentwise on the entries of the matrix.
The matrix division deserves some special comments. If A is an invertible square
matrix and b a compatible column resp. row vector, then

2. Introduction into MATLAB

>> x = A \ b gives the solution of the linear system A x = b , i.e. x = A1 b


>> x = b / A gives the solution of the linear system x A = b , i.e. x = b A1 .
In left division, if A is square, then it is factored using Gaussian eliminations. If A is
not square, it is factored using Householder orthogonalization with column pivoting.
The factors are used to solve the under- or overdetermined system in the least squares
sense. Right division is defined in terms of left division by b/A = (A \ b).
The matrix operations of addition and subtraction are defined entry-wise but all other
operations are matrix operations. It is important to mention that these other operations *, , \ , / can also be evaluated entry-wise by preceding them by a dot, e.g.
>> a1 = [1 2 3] * [1;2;3] = >> a1 = 14
>> a2 = [1 2 3] .* [1 2 3] = >> a2 = [1 4 9]
Analogously,
>> b2 = [1;2;3]. 2 = >> b2 = [1;4;9]
Build-in functions:
if arbitrary build-in functions for scalars, e.g. exp(), sqrt(), sin(), are applied on matrices, they are evaluated componentwise.
a few build-in functions in MATLAB deal with the whole matrix and not only
with its components, e.g. expm(), sqrtm(), logm().
Vector functions: length()length,
max()
maximum,
sum()
sum of components,
sort() sorting,
mean() mean,
any()
any non-zero values?

norm() norm
min()
minimum
prod() product of components
median() median
std()
standard deviation
all()
all non-zero values?

Matrix functions: size()


inv()
norm()
eig()
lu()
schur()

rank()
det()
cond()
chol()
qr()
hess()

size,
inverse,
norm,
eigenvalues,
LU-decomposition,
Schur complement,

Matrix building functions:


zeros()
ones()
eye()
rand()
diag()
toeplitz()

rank
determinant
condition
Cholesky-decomposition
QR-decomposition
Hessenberg form

matrix of zeros
matrix of ones
identity matrix
randomly generated matrix
create or extract diagonals
see help toeplitz

For example, zeros(m,n) produces a (m n) -matrix of zeros and zeros(n) one of


size (n n) . The command zeros(size(A)) generates a matrix of zeros having the
same size than the matrix A. Analogously for ones(), eye(), rand(). Moreover,
matrices can be build from blocks:

10

2. Introduction into MATLAB

>> A = rand(3,3);
>> B = [A, zeros(3,2); zeros(2,3), eye(2)];

yields a (5 5) -matrix.

Addressing matrix components:


A(m,n)
: the component amn of the matrix A = (aij )ij .
Note that the numbering of the components starts from 1.
A(m:n,p) : the m until the n th row of the p th column of the matrix A
A(:,n)
: the complete n th column of the matrix A
A([m,n],:) : the m and the n th row of the matrix A
x(m)
: the m th component of the vector x
x = x(n:-1:1) changes the order of the elements of the vector x of length n
The components of a vector can be either addressed by the standard two arguments
for row and column or alternatively by a single argument (the respective other one is
by default 1) as exemplified above. The last has the advantage that row and column
vectors can be treated similarly. The command length() provides the length of a
vector, the command size() the size of a matrix, e.g.
>> A = [1 2 3; 4 5 6]; size(A) = ans = [2,3]

2.7

Control Structures and Logical Operators

Like other computer languages, MATLAB has the control structures for, while and
if. For and while-loops slow MATLAB down, try to avoid them and use instead
matrix-vector operations.
For:
The general form of a for-loop is
for counter = start value:increment:end value
statements
end
The statements are executed for all values of the counter variable, see
v = zeros(1,n);
for i = 1:2:n
instead, better:
v(i) = sin(2*pi*i/n);
v(1:2:n) = sin(2*pi*[1:2:n]/n);
end
While:
The general form of a while-loop is
while relation
statements
end
The statements are repeatedly executed as long as the relation remains true, e.g.
a = 1; i = 1;
while a > 0
instead, better:
v(i) = sqrt(a);
v = sqrt([1:-0.1:0.001]);
i = i-1;

2. Introduction into MATLAB

11

a = a-0.1;
end
If:
The general form of a simple if-statement is
if relation
statements
end
The statements are executed only if the relation is true. Multiple branching is also
possible, as illustrated by
if relation A
statements A
elseif relation B
statements B
else
statements C
end
Consider for example the building of a lower triangular matrix
if i==j
A(i,i) = 1
elseif i>=j
A(i,j) = -1
else
A(i,j) = 0
end
less than
Relational operators: <
>
greater than
<= less than or equal
>= greater than or equal
== equal
= not equal
Note that the equality sign = is used in an assignment statement whereas == is used
in a relation. Relations may be connected or quantified by logical operators.
Logical operators:

&
|

xor
Further useful operators are

and
or
not
exclusive or
any and all.

Applying the listed operators above on scalars, the result is 1 or 0 depending on


whether the relation is true or false. When applied to matrices of the same size, a
relation yields a matrix with 1 and/or 0 as entries, e.g.
>> A=([1 4 -5]>[1 1 1]) = >> A = 0 1 0
A relation between matrices is interpreted by while and if to be true if all entries of
the relation matrix are non-zero. Hence, if A==B statements end is only executed

12

2. Introduction into MATLAB


if the matrices are identical.

2.8

M-Files: Script and Function Files

MATLAB can execute a sequence of statements stored in diskfiles. Such files are called
m-files because they must be saved with .m as the last part of their filename. M-files
are usually created by using the local text editor. There are two types of m-files: script
and function files.
Script file:
contains a sequence of standard MATLAB commands that could alternatively
be given interactively in a MATLAB session
is executed by calling its name in the command line, i.e. if the file is saved as
test.m then type test in the command line
yields the same output as the step-wise manual input of all contained commands
has global variables and thus changes the value of variables with the same name
in the workspace of the current MATLAB session
can call other M-files, including itself recursively
Script files may be used to enter a lot of data into huge matrices, since entry errors
can be easily corrected.
Useful build-in functions: input, keyboard, pause, disp
Function file:
provides the extensibility to MATLAB, since it prescribes a function that has
been specifically created to the arising problem
has the same status as the other build-in functions
has local variables. The defined variables are not saved in the global workspace!
A function called myf must be saved in the function file myf.m whose first line must
read
function myf
The function has m input and n output parameters if the first line declares additionally to the function name also the input and output parameters in the following
form
function [out1,out2,...,outn] = myf(in1,...,inm)
This line is essential for the execution of the function. Without these declarations the
file would be a normal script file.
Take for example the function file operation.m
function [sum, prod] = operation(a,b)
% [sum,prod] = operation(a,b)
% computes sum and product of two input parameters a,b of same size
sum = a+b;
% computes the sum
prod = a*b;
% computes the product
Call the function in the command line by
input: >> [a,b] = operation(3,5)
=

output: >> a = 8

>> b = 15

2. Introduction into MATLAB

13

input: >> [C,D] = operation(ones(2),eye(2))


>> C = 2 1
>> D = 1 1
= output:
1 2
1 1
A function can be called without the full set of input and output parameters by help
of the commands nargin and nargout.
nargin: number of input arguments by call
nargout: number of output arguments by call
Further useful build-in functions: return, eval
Note that a good programming style requires the commenting of m-files. Comments
are included by the percentage symbol %, more precisely the text in the line following %
is the comment. The command help m file name returns the first connected block of
comments stated in the m-file. Such a block is finished by an empty row or a MATLAB
expression.

2.9

Graphics

MATLAB can produce 2D and 3D plots of curves, 3D mesh surface plots as well as
3D faceted surface and 3D contour plots. The primary commands are plot, plot3,
mesh, surf and contour, respectively. For a detailed description see the on-line help,
here only a brief introduction in 2D plotting is provided.
The command plot creates linear x-y plots. If x and y are vectors of same length, the
command plot(x,y) opens a graphics window and draws an x-y plot of the elements
of x versus the ones of y , e.g.
>> x = -1:0.01:1; y = sin(x); plot(x,y)
analogously,
>> s = -10:0.01:20; t = exp(-s. 2); plot(s,t)
By default, the plot command always opens figure(1) and overwrites the old graphics. If a current graphics window (figure) should be kept, another one can be opened
with the command figure(2) or simply figure which then becomes the current figure
where graphs from subsequent plotting commands will be placed.
Multiple plots can be made in a single figure by using the command
>> plot(x,y,s,t)
or
>> plot(x,y); hold on; plot(s,t); hold off
For plotting specified line types, marker types and colors can be chosen, for example
>> plot(x,y,r--,s,t,b:+)
renders a red dashed line for the first graph and a blue dotted one for the second one
where additionally the nodes are marked by the symbol +.
Line types:

- solid, -- dashed, : dotted, -. dash-dotted

Marker types: . point, + plus, * star, o circle, x x-mark

2. Introduction into MATLAB


Colors:

y yellow,

14

m magenta, c cyan, r red, g green, b blue, k black

The graphics can be given titles, axes labeled and text placed within the graph using
the following commands which take a string as argument: title, xlabel, ylabel,
gtext resp. text.
The command subplot can be applied to partition the screen so that several small
plots can be placed in one figure, see help subplot.
Other specialized 2D plotting functions that are worth to be explored via help are
polar, bar, hist.

2.10

Further Useful Commands

for comparing the efficiency of algorithms: flops, etime, tic, toc, cputime
for generating a log.file that saves all commands of the recent session: diary
for visualizing 3D-graphics and generating animations: plot3, mesh, surf,
surfc, contour, axis
for dealing with text strings: string, eval, num2str, disp
for ensuring the efficient computation and storage of large, but sparse matrices:
spdiags, speye, spones, sparse, full
for debugging MATLAB functions and script files: dbstop, dbclear, dbcont
The scope and power of MATLAB go far beyond these notes. Be aware that this
chapter is only meant to give a brief survey of the possibilities and the build-in
functions in MATLAB, and it is certainly far away from completeness. Hence, do not
hesitate to consult the MATLAB Users Guide, Reference Guide or the on-line help
to get more detailed and updated informations.

3. Exercises

15

Exercises

The following exercise tasks taken from the fields of differential equations, statistics
and stochastics are designed for a constructive self-study in programming. Every task
requires some new MATLAB features that are provided in the list of helpful buildin functions. Once introduced, the features should be continuously applied in the
ongoing tasks such that they become familiar to the user. Since programming lives
from practice, it is recommended to supplement the given tasks by further examples
of interest, e.g. other one-step methods, finite difference and element methods [4],
interpolation and extrapolation routines [5] or optimization problems.

3.1

MATLAB as Interactive Calculator

1. Try the calculation operations and build-in functions for real and complex numbers
15 2; (4.6+6i) - (1.5+3i); 2.5*(2.79e-10); (20e+14)/145
What is the difference between the left and right division 7/2 and 2 \ 7?
absolute value: abs(-3+5i); square root: sqrt(2); real part: real(5+3i);
imaginary part: imag(5+3i); round: round(4.5130); signum: sign(-3)
Use also exp( ); log( ); sin( ); cos( ); tan( ); gamma(); bessel( ).
What do you observe for the last function?
2. Introduce vectors and matrices into the MATLAB working space
Enter the vector (1 5.6 27+8i 6 103) as row and as column vector.


1
5
7
Enter the matrix
.
4 + i 27.5 104
What kind of brackets are required?
3. Define variables (MATLAB distinguishes between capital and small letters!)
a1 = 4; a2 = [4:2:10], A1 = This is a text.
What is the output?
Enter the command who. What is MATLABs answer?
Enter the command clear and afterwards who.
What is MATLABs answer now?
Try the already defined variables pi, eps.
Find out the difference between the input a = a1+2 and a = a1+2;
What is the consequence of the semicolon after the statement?
4. Try matrix-vector operations

1 2 3
17
Define A = 4 5 6 , B = 3A + I and b = 19 in MATLAB
7 8 9
21
33
where I R
denotes the identity matrix.

3. Exercises

16

Compute AT , A B , A B , A2 (i.e. A A ), A1 B , A B1 .
Compare the output of 1/B, eye(3)/B and inv(B).
What is A*b? What is b*A?
How can the last expression be modified such that MATLAB accepts the
input?
Try c = b*b, c= b*b and c=b.*b. Explain the obtained outputs.
Address vector components. What is the output of b(1)?
Address matrix components. What is the output of A(1,1)? A(1,:)?
A(:,3)? Pick out the 1st and 2nd row of the matrix B = (Bij )ij by means
of the command B([1,2],:). How can you extract the component B1,3 ?
Generate special matrices. Try eye(3), zeros(3,4), ones(2,3), rand(3,3)
and again rand(3,3). What is the output of diag(b)? And of diag(A)?
What is the output of C = [A, zeros(3,2); zeros(2,3), eye(2); 1:5]?
What is the output of C([1:3],[2:4])?
5. Visualize functions
Enter x = 0:pi/8:2*pi; plot(x,sin(x)).
What happens by the command figure? What by figure(10)?
Enter y = linspace(0,1,10); plot(y,y. 2).
Discover the tool bar at the top of the plot window.

3.2

M-Files in MATLAB

? Statistical Evaluation of Data


Step 1:
Write a function statistics.m in MATLAB
function [mean,stdev]=statistics(x)
that computes for a given vector x the mean mean and the standard deviation stdev
of its components. Note that the input vector x might be a row or a column vector
of various length. Do not forget the description of the function in the first comment
line, remember comments start with %.
Helpful build-in functions: size(), sum(), sqrt()
Step 2:
Test your function with the following input vectors:
y1 = (11 1 3 9 5 7)

10
6

y2 =
12
20

y3 : vector with random components and arbitrary length n, n > 0

17

3. Exercises

Compare your results with the ones being obtained from the MATLAB build-in functions mean() and std().
Helpful build-in functions: rand()
Step 3:
1. Generate a random input vector y of length n , n > 1000 .
2. Call your function statistics for the determination of its mean mean and its
standard deviation stdev.
3. Visualize the input vector, its mean and standard deviation graphically. Therefor, proceed in the following way:
a) Enter the vector t=[1:n] where n equals the length of y .
b) Plot your input data vector by help of the command plot(t,y,ko).
c) Type hold on.
d) Define a vector v of length n whose components are equal to 1.
e) Plot your mean by help of the command plot(t,mean*v,r-).
f) Plot your standard deviation around your mean by help of the command
plot(t,mean+stdev*v,b-.) resp. plot(t,mean-stdev*v,b-.).
g) Type hold off.
Helpful build-in functions: rand(), ones()
Questions:
What do the commands hold on, hold off do?
What happens if you use plot(t,mean,r-) for visualizing the mean? Why?
What is the effect of the 3. argument in the plot() function?
What is the meaning of ko, r-, b-. ?
Possible Extension:
Extend your function statistics.m such that it computes also the median and plots
the probability distribution function.

3.3

If, For, While,


Text Output and Editing Graphics

? ODE: Stability and Explicit Euler Method


Goal:
Consider the first order system of linear ODEs
x0 (t) = y xg = f1 (x, y),

y 0 (t) = x yg = f2 (x, y),

gR

(3.1)

Write a function stability.m in MATLAB


function stability(g,x0,y0,tau)
that determines the stability of the system for the input parameter g and plots the
corresponding trajectory for the given initial values x0, y0 and step size tau.

18

3. Exercises
Step 1:
The system (3.1) is prescribed by the matrix


g 1
A=
.
1 g
The eigenvalues 1 , 2
maxi Re(i ) < 0
maxi Re(i ) = 0
maxi Re(i ) > 0

of A

determine the stability behavior of the system:


system is asymptotically stable
system is stable, since index i(i ) = 1
system is instable

Write a function stability1.m in MATLAB


function stability1(g)
that computes the eigenvalues for varying g and displays the stability behavior of the
corresponding system on the screen. Test it! (Compare with [4] , Exercise Task 2.1)
Helpful build-in functions:
eig(): computes the eigenvalues of a matrix
if relation A statement A;
elseif relation B statement B;
else
statement C;
end
if-condition: if relation A is valid, then statement A is evaluated, otherwise if
relation B is valid, statement B, else statement C.
num2str(): converts a number into a string
disp(): displays a string on the screen (text output)
Examples:
a) disp(This function determines the stability behavior of the
given linear system.);
b) g=0.5; disp([For g= ,num2str(g), the eigenvalues of the system
are ... and thus the system is ...]);
Step 2:
The trajectory (discrete evolution) of the system with respect to given initial values
x0 = x(t0 ), y0 = y(t0 ) and time step can be computed by means of the explicit
Euler method:
xn+1 = xn + f1 (xn , yn ),

yn+1 = yn + f2 (xn , yn ).

Write the extended version stability2.m based on stability1.m


function stability2(g,x0,y0,tau)
that additionally computes and visualizes the trajectory of the solution for given initial
values x0, y0 and time step tau. Let the starting time t0 for your computation be
tStart=0 and choose the final time tEnd appropriately. Store the computed values
xn , yn as components in corresponding vectors x and y. Plot the vector x against y.

19

3. Exercises

The initial values should thereby be marked by a red circle and the trajectory plotted
by a solid black line. Try different initial values and varying step sizes.
Helpful build-in functions: For and while-loops
For-loop: for counter=start value:increment:final value statements; end
In a for-loop, a counter runs from a starting value to a final value. After having evaluated the inner statements, the counter is updated by the arbitrary chosen increment
and the inner statements are evaluated with the new value of the counter. For-loops
are the appropriate tool for implementing recursions (cf. right example). Note that in
certain cases (left example) for-loops should be replaced by vector-matrix operations
to speed up the MATLAB computations.
Examples:
h=2; n=10; a=3; z=zeros(1,n+2);
for k=1:4
for k=1:h:n

z(k)=k 2;
z(k+2)=z(k)+h*a-k 3;
end
end
instead better:
z(1:4)=[1:4]. 2;
While-loop: while relation statements; end
In a while-loop, the loop is evaluated as long as the relation is true. A while-loop
might be used similarly to a for-loop, if the relation reads counter < = final value.
But then the starting value of the iteration must be set manually before the loop, and
the counter must be updated manually in the loop, cf. middle example. On the other
hand, while-loops are very appropriate for implementing recursions with additional
breaking conditions (right example) .
Examples:
k=1
k=1; h=2; n=10; a=3; z=zeros(1,n+2); n=0; a=30;
while k<=4
while k<=n
while 2 n<a
z(k)=k^2;
z(k+2)=z(k)+h*a-k^3;
n=n+1;
k=k+1;
k=k+h;
end
end
end
n
instead better:
z(1:4)=[1:4]. 2;
Step 3:
Save your function stability2.m as stability3.m. Extend stability3.m in such a
way that you are able to read in an array of starting values for x0 and y0, respectively.
Compute in only one loop the trajectories for the set of all different starting values.
How must you arrange the data structure of x and y to fulfill this task? Plot all
trajectories in one single figure. For the plotting you might need an other loop.
Question:
How do the trajectories change if you vary the step size in particular in the stable
case?

20

3. Exercises
? ODE: Importance of Step Size in Explicit One-Step Methods
Consider the following initial value problem
y 000 (x) + y 00 (x) + y 0 (x) + y(x) = 0,

y(0) = 0, y 0 (0) = 1, y 00 (0) = 2

(3.2)

that is taken from [4] , Exercise Task 3.1.


1. Transform Eq (3.2) into an equivalent system of first order.
2. Compute the numerical solutions of y , y 0 and y 00 for x [0, 2] by help of the
explicit Euler method.
3. Plot the numerical results for different step sizes h {1, 0.5, 0.25, 0.1, 0.01, 0.001}
in one figure (i.e. one figure for all approximations of y , one for y 0 and one for
y 00 ) and compare them with the analytical solution
y(x) = cos(x) + 2 sin(x) + exp(x).
Helpful build-in functions:
The figures can be given titles, axes labeled and text placed within the figure with the
following commands which take a string as argument:
title()
xlabel()
ylabel()
gtext()
text()

figure title
x-axis label (horizontal axis)
y-axis label (vertical axis)
place text on the graph using the mouse
position text as specified coordinates (see help text)

Example: title(Numerical Solution for y);


For distinguishing and labeling different functions in one figure the command legend
might be also useful (see help legend).
? ODE: Convergence Order
Explicit Euler vs Explicit Classical RungeKutta Method
A simple model for the predator-prey relationship (e.g. between snakes and mice) is
given by the following system of differential equations
x0 (t) = x(t) + x(t)y(t)
y 0 (t) = y(t) + x(t)y(t)
where x and y represent the number of creatures per species. Implement the classical
(standard) explicit RungeKutta method with the parameters
1
= ,
4

1
,
100

= 1,

x0 = 80,

y0 = 30

the initial values

1
,
100

21

3. Exercises

and the step sizes h {1, 0.5, 0.1} . Compare the results with the respective approximations given by the explicit Euler method for the same step size. Plot therefor the
coordinates (xi , yi ) . Choose for your computations the time interval t [0, 20] .
Recall: Scheme of classical explicit RungeKutta method [4]
Consider the arbitrary system of ODEs x0 (t) = f (t, x) with step size h , then the
general RungeKutta scheme (b, c, A) with s levels reads
xn+1 = xn + h

s
X

b i ki

i=1

k1 = f (tn + h c1 , xn )
ki = f (tn + h ci , xn + h

i1
X

aij kj ),

i = 2, ..., s

j=1

In the classical RK-method s = 4 , the coefficients are given by the following Butcher
array
c1
c2
c3
c4

a11
a21
a31
a41
b1

a22
a32
a42
b2

a33
a43
b3

a44
b4

0
0
1/2 1/2 0
1/2 0 1/2 0
1
0
0
1
0
1/6 1/3 1/3 1/6

? Algorithmic Programming: Sorting and Searching Routines


Write a function search.m that compares the value x with the components of the
vector v and states whether or not x is contained in v:
function flag = search(x,v)
Input: scalar x, vector v
Output: scalar flag: flag = 1 if x in v, otherwise flag = 0
Method:
There are plenty of methods how you can program such a search algorithm especially
by means of MATLAB build-in functions.
But try a binary search:
Firstly, the vector v is sorted, then x is compared with the element in the middle of
the vector. If x is smaller than this value, the search is restricted on the lower half
of the vector, otherwise on the upper one. In the next step, x is compared with the
element in the middle of the respective half. This division into two parts is continued
until the value x is found or the region is empty.
For the sorting, you might use the build-in function sort(), but you can also write
your own sorting function mysort.m
function sortv = mysort(v)

22

3. Exercises

3.4

ODE-Solvers and Efficiency of Algorithms

? ODE: Implicit One-Step Methods, Newton Method


Solve the Van-der-Pol equations
x0 = y,
y 0 = 10 (1 x2 )y x,

x(0) = 2,
y(0) = 0,

numerically on the interval t [0, 20] .


1. Introduce zn := (xn , yn )T and discretize the Van-der-Pol equations with the implicit Center-point rule zn+1 = zn + f ((zn + zn+1 )/2) with step size = 103 .
2. Solve the arising non-linear system of equations F(zn+1 ) = 0 with the Newton
method and use hereby the values of the previous time step as initial values for
(0)
the iteration, i.e. zn+1 = zn . Stop the iteration, if the difference of the iteration
(k+1)
(k)
values satisfies kzn+1 zn+1 k 108 .
3. Plot the resulting (x, y) -values, plot the number of required iteration steps over
the time steps.
4. MATLAB provides certain build-in routines for solving ODEs, e.g. ode23s,
ode15s, ode23t, ode23tb. Use help to study the comments and syntax for
the respective routines and test them on the Van-der-Pol equations.
5. Compare the number of function evaluations (flops) and the required time for
the total computation (tic, toc). Which method is the most appropriate one
for solving the Van-der-Pol equations?
6. Try to speed up the method by providing the inverse of the Jacobian matrix
analytically.
Helpful build-in functions:
norm(): computes the norm of a vector
ode23s, ode15s, ode23t, ode23tb: ODE-solvers
tic, statement, toc: returns the elapsed time (in seconds) for executing the
statement
flops(0), statement, flops: returns the number of flops performed for the
execution of the statement
Example: flops(0), tic, x=A \ b, toc, flops
This statement returns the elapsed time and number of flops for solving the linear
system. Use alternatively, x=inv(A)*b, compare the required time and flops. Which
method is more efficient for solving a linear system?

23

3. Exercises

3.5

Matrix Manipulations, Sparse Matrices and 3D-Plots

? PDE: Finite Differences


Discretize the Poisson equation
4u(x, y) = f (x, y)
on the domain = (0, 1)2 by means of the 5-point-difference stencil
4uij

1
(ui1,j ui,j1 + 4ui,j ui+1,j ui,j+1 )
h2

with h =

1
25

and state the resulting linear system Lh uh = fh for a row-wise numbering. Compute
the approximations for the following problems and visualize them graphically:
f (x, y) = 1 in
f (x, y) = 0 in

and
and

u(x, y) = 0 on ,
u(x, y) = x2 on .

Possible Extension:
1. Modify the 5-point stencil in such a way that h is the step size in x -direction
and k in y -direction.
2. Compute the approximations of the problems for different tuples (h, k) of step
sizes, h {1/10, 1/20, 1/25, 1/50, 1/100} , k {1/10, 1/20, 1/25, 1/50, 1/100}
and measure elapsed time and number of operations.
3. Use the approximation with respect to h = k = 1/100 as reference solution
and determine and plot the numerical errors. Are there any relations between
maximal error, number of grid points, elapsed time and number of operations?
4. Think about an irregular grid, i.e. 0 = x0 < x1 < ... < xM = 1 and 0 = y0 <
y1 < ... < yN = 1 with hi = xi xi1 and kj = yj yj1 , and derive a 2D-stencil
from the 1D-discretization given in [4], Exercise Task 6.2


2
ui ui+1 ui ui1
00
+
u (x)
.
hi + hi+1
hi+1
hi
5. Design your own irregular grid and apply your stencil.
Helpful build-in functions:
Matrix manipulations:
diag(v,k): generates a quadratic matrix with the vector v on the k th (sub-)
diagonal. k = 0 : main diagonal, k > 0 : upper subdiagonals, k < 0 : lower
subdiagonals
tril(A): extracts the lower triangular matrix from the quadratic matrix A
triu(A): extracts the upper triangular matrix from the quadratic matrix A
fliplr(A): flips the matrix A from left to right
flipud(A): flips the matrix A from up to down

3. Exercises

24

rot90(A,k): rotates the matrix A counterclock-wise around k *90 degrees


repmat(A,m,n): generates a matrix that contains m n copies of A
reshape(A,m,n): generates a m n matrix B that is column-wise filled up
with columns of A . Note that (number of entries in A )= m n .
3D-plots:
linspace(start value,end value,n): generates an equidistant grid on the interval [start value,end value] with n grid points. Note that start value
and end value belong to the grid points.
logspace(start value,end value,n): generates a logarithmic grid on the interval [start value,end value] with n grid points. Note that start value
and end value belong to the grid points.
plot3(x,y,z): plots the vector x vs y vs z .
plot3() can be called with the same properties as plot()
Examples:
a) plot3(x,y,z,-.mo): plots a dash-dotted magenta line with circles
b) plot3(x,y,z,:b*,LineWidth,3,MarkerSize,8,...
...,MarkerEdgeColor,k,MarkerFaceColor,r):
plots a dotted blue line of width 3 with red stars of size 8 as markers whose
edges are black-colored
Moreover, commands such as grid, xlabel, ylabel, zlabel, title can be
applied.
[X,Y] = meshgrid(x,y): generates from the vectors x , length(x)=n, and y ,
length(y)=m, two m n matrices X , Y where X contains row-wise copies of
x and Y column-wise copies of y
surf(X,Y,Z): generates a surface plot of the matrix Z on the 2D-grid given by
the matrices X and Y . Note that X , Y and Z must be of same size.
surfc(X,Y,Z): generates a surface plot of the matrix Z on the 2D-grid given
by the matrices X and Y and additionally a contour plot. Note that X , Y
and Z must be of same size.
contour(X,Y,Z,n): generates a contour plot with n level curves of the matrix
Z on the 2D-grid given by the matrices X and Y . Note that X , Y and Z
must be of same size.
Example:
[X,Y] = meshgrid([-2:.2:2],[-2:.2:3]);
Z = X.*exp(-X. 2-Y. 2);
figure(1), surf(X,Y,Z), figure(2), surfc(X,Y,Z),
figure(3), contour(X,Y,Z)
Sparse matrices:
spalloc(m,n,p): allocates space for a matrix of size m n with p non-zero
entries
speye(n): generates a sparse identity matrix of size n n

25

3. Exercises

spdiags(v,0,n,n): generates a sparse quadratic matrix of size n n with the


vector v on the diagonal
sparse(A): converts a full matrix into a sparse one
full(A): converts a sparse matrix into a full one

3.6

Nargin, Switch, Polynomial Functions and


M-File Management

? MonteCarlo Simulation
Implement a random walk and compare its analytical and numerical expectations.
Therefor, consider a discrete stochastic process (t , t {0, 1, ..., T }) with independent
identically distributed increments t = t t1 {u, d} , u , d 0 . Then, a
random walk reads
t
X
t = 0 +
i , t = 1, 2, ...T
i=1

where the probability of the increment i being u is given by p and respectively of


being d by (1 p) , p [0, 1]
P(i = u) = p,

P(i = d) = (1 p)

for all i.

The analytical expectation (mean) of the value t at time t is prescribed by


E[t ] = E[0 ] + t((u + d)p d).
The numerical expectation of the random variable t can be computed by help of
MonteCarlo simulations. Therefor, observables of t are generated
Pn in n independent simulation runs, whose values are then averaged, i.e. t = i=1 (t )i /n . For
comparing analytical and numerical expectation, plot the probability distribution function for the observables of t and visualize the analytical mean as red solid line and
the numerical one as blue dashed line (line width 2). The plotting requires that the
number of simulations n is treated as 100% and thus scaled as 1 and that the respective percentages are drawn over the sorted values of the observables ( t )i as black
stars (marker size 6). For n the obtained probability distribution function is
a normal distribution where analytical and numerical mean coincide. Visualize this
relation by plotting the error over n .
Implementation:
function [mean n,mean a,error] = random walk(P0,p,u,d,t,n)
% [mean n,mean a,error] = random walk(P0,p,u,d,t,n)
% simulates a random walk, computes its numerical mean mean n at time t
% by using n Monte-Carlo simulations with respect to starting value P0,
% probability p and increments u and d and
% compares it with the analytical mean mean a by plotting probability
% distribution function and determining the error

26

3. Exercises

%
%
%
%
%
%

alternatively: [mean n,mean a,error] = random walk(P0)


then by default: n=100, t=100, u=d=10, p=0.5
alternatively: [mean n,mean a,error] = random walk(P0,p,u,d)
then by default: n=100, t=100

Helpful build-in functions:


nargin: pre-defined variable by MATLAB. Calling a function, MATLAB stores automatically the used number of input arguments in nargin. If nargin does not coincide
with the number of inputs stated in the declaration line of the function, default values
must be provided. Analogously, nargout for number of output arguments by call.
? Numerical Integration
Perform numerical integration by help of NewtonCotes quadrature rules and Monte
Carlo simulations. Therefor, consider an arbitrary function f : I R , I = [x0 , xN ] .
Its integral can be determined by quadrature rules, e.g.
Z x0 +h
h
f (x) = (f (x0 ) + f (x0 + h) + O(h3 )
Trapezoid rule
2
x0
Z x0 +2h
h
f (x) = (f (x0 ) + 4f (x0 + h) + f (x0 + 2h)) + O(h5 )
Simpson rule
3
x0
The quality of the approximated integral depends on the integral length h . Thus, it
is reasonable to introduce an equidistant grid xi = i h , i = 1, ..., N and divide I into
smaller subintervals Ii = [xi1 , xi ] .
Alternatively, a MonteCarlo simulation can be used for the computation of the integral. Since the integral represents the area between the x -axis and the graph of the
function, one might embed the function into an rectangle as visualized below.
3.75
3.25
2.75
2.25
1.75
1.25
0.75
0.25
0.25
0.25

0.25

0.5

0.75

1.25

Figure 3.1: Integral represents area of marked region.

3. Exercises

27

Generating m random points within this rectangle of size A , one counts the number of points p laying in the area of interest. Then, the integral of the function is
approximated by
Z xm
p
f (x)dx A.
m
x0
Repeating this procedure n -times yields an reasonable numerical expectation for the
integral.
Implementation:
% script file integration.m
% defines the considered function f as string and the interval I as
%
vector of start and final point,
% initializes the number of grid points for the quadrature rule and m
%
and n for the Monte--Carlo simulation,
% calls the functions quadrature.m and monte carlo.m,
% visualizes the distribution function for the observables as well as
%
the numerical and the analytical mean,
% visualizes the approximate integral values and errors over h and
%
respectively over n
%
%
%
%

function file quadrature.m


computes the integral by help of quadrature rules,
whose choice depends on the input flag, e.g.
flag=Trapezoid or flag=Simpson

% function file monte carlo.m


% computes the integral stochastically using Monte-Carlo simulation
Helpful build-in functions:
eval(): evaluates a string
Example: f = exp(x); x = 0; eval(f) = ans = 1
feval(): evaluates a defined function
Example: x = 0; feval(exp,x) = ans = 1, easier: exp(x)
switch, case, otherwise: comparable to if, elseif, else but for text strings
Syntax: switch switch expression
case case expression statement
otherwise
statement
end
Example: switch flag
case Trapezoid integral = T;
case Simpson
integral = S;
otherwise
error(Unknown flag);
end
Compare your results with the ones due to the build-in functions:
trapez(): Trapezoid rule
Example: x = 0:pi/8:2*pi; y = sin(x); integral = trapez(x,y);

28

3. Exercises

quad(), quad8(): quadrature rules based on adaptive Newton-Cotes formulae


? Curve Fitting Routines
Implement least-square curve fitting routines (linear, quadratic, cubic and exponential). Let the observed data be given by n tuples (xi , yi ) , i = 1, ..., n . In a polynomial
fitting ansatz of degree p , the error reads
2

e (a0 , ..., ap ) =

n
X
i=1

(yi

p
X

ak xki )2

k=0

The coefficients ai are determined in such a way that the error is minimal with regard
to least squares, i.e.
e2 (a0 , ...ap )
= 0, for k = 0, ..., p
ak
which leads to (p + 1) equations for (p + 1) unknowns.
In case of p = 1 , the equations are then for example
n

X
e2 (a0 , a1 )
= 2
(yi (a0 + a1 xi )) = 0
a0
i=1
n

X
e2 (a0 , a1 )
= 2
(yi (a0 + a1 xi ))xi = 0
a1
i=1
An exponential fitting ansatz can be rewritten in terms of the linear one, since
yi = c0 exp(c1 xi )

ln(yi ) = ln(c0 ) + c1 xi .

Compare your results with the ones due to the build-in function polyfit().
Helpful build-in functions:
polyfit(x,y,d): fits the given data x and y by a polynomial of degree d and
returns its coefficients in the order from xd to x0
polyval(p,x): evaluates the polynomial prescribed by the coefficient vector p
at the values x
roots(p): determines the roots of the polynomial prescribed by the coefficient
vector p

4. Possible Implementations and Further Comments

29

Possible Implementations and


Further Comments

The presented implementations should be understood as sample programs for the exercises and not as unique solution. Alternative implementations for the same algorithm
are always possible. Depending on the experiences with MATLAB, varying programs
of complexity are given for the same task in the following. The basic ones apply only
the already known MATLAB functions, whereas the extended ones introduce new and
interesting features that are worth discovering in detail. Apart from implementation,
this chapter focuses also on the discussion of the simulation results in terms of scientific computing. Thereby, the evaluation of the numerical results always requires the
understanding of the underlying analytical concept.

4.1

MATLAB as Interactive Calculator

This exercise is meant as practical help-line to get familiarized in MATLAB and is


easily doable by help of the introductory part in Ch 2. In particular, it should give
an insight into the powerful tool of MATLAB as interactive calculator, raise curiosity
and encourage to further independent studies and application.
MATLAB Warnings and Error Messages:
MATLAB checks the syntax of the input commands and states warnings and error
messages on the screen in case of mistakes. Thereby, it helps the user by already
giving ideas what and where (in which line) the mistake could possibly be, e.g. missing
bracket, missing comma or semicolon, capital starting letter for a function name, sizes
of matrices are incompatible for certain operations. MATLABs suggestions are mostly
absolutely correct such that it is worth studying and following them. If function and
variable names are spelled wrongly or do not exist in the workspace, MATLAB states
a list with alternatives whose spellings are similar and might be meant. Hence, if
one does not know or remember a name precisely, it makes sense to try out reasonable
names like for example bessel(5) in Task 1. In this way, one finds out that MATLAB
has a bunch of bessel functions, i.e. besseli(), besselj(), besselk(), bessely()
that expect different input arguments. To get more information about the respective
functions and their syntax call help function of interest. Moreover, MATLAB
produces warnings if the results of certain operations are not reliable, e.g. division by
zero or inversion of a singular matrix (cf. Task 4, A1 B ). The respective operations
should then be checked and modified and the results not used for further calculations.

4.2

M-Files in MATLAB

This exercise calls for writing the first own m-file in MATLAB. In particular, it is
a function file that outputs mean and standard deviation for a variable input data
vector.

4. Possible Implementations and Further Comments

30

? statistics.m
function [mean,stdev] = statistics(x);
% [mean,stdev]=statistics(x)
% computes mean and standard deviation of an arbitrary vector x
% =============================================================
% computation of length of x
[p,q] = size(x);
% gives number of rows p and columns q of x
% valid for general matrices
n = p*q;
% alternatively:
% n = length(x);
% only valid for vectors
% computation of mean
mean = sum(x)/n;
% computation of standard deviation
stdev = sqrt(sum((x-mean).^2)/n);
% plot of the statistical properties
t = [1:n];
plot(t,x,ko);
hold on;
v = ones(1,n);
plot(t,mean*v,r-);
plot(t,mean+stdev*v,b-.,t,mean-stdev*v,b-.);
hold off

Extension:
The program statistics.m can be extended in such a way that additionally the
median of the input data vector is computed. For sorting the input vector and finding
the position of the median, the MATLAB functions sort() and if-condition are
applied in statistics ext.m. Moreover, the simple plotting routine producing Fig 4.1
is replaced by the graphical visualization of the probability distribution function in
Fig 4.2. To emphasize the median as big red circle, the MarkerSize is increased upto
12 in the plot command (see help plot for further options).
Used build-in functions: if-condition, sort(), linspace(), plot()

function [mean,stdev,median] = statistics_ext(x);


% [mean,stdev,median]=statistics_ext(x)
% computes mean, standard deviation and median of a vector x
% ==========================================================

31

4. Possible Implementations and Further Comments


1

0.9

0.9

0.8

0.8

0.7

0.7

0.6

0.6

0.5

0.5

0.4

0.4

0.3

0.3

0.2

0.2

0.1

0.1

0
0

20

40

60

80

100

0
0

200

400

600

800

1000

Figure 4.1: (statistics.m) Distribution of the x -components around their mean


(red solid line) within the bounds [, +] (blue dashed line) for different samples.
Left: x=rand(1,100), Right: x=rand(1,1000).
1

0.9

0.9

0.8

0.8

0.7

0.7

0.6

0.6

0.5

0.5

0.4

0.4

0.3

0.3

0.2

0.2

0.1

0.1

0
0

0.2

0.4

0.6

0.8

0
0

0.2

0.4

0.6

0.8

Figure 4.2: (statistics ext.m) Probability distribution function for the samples of
Fig 4.1. Median is marked by red circle, by red solid, by blue dashed line.

n = length(x);

% length of x

% computation of mean
mean = sum(x)/n;
% computation of standard deviation
stdev = sqrt(sum((x-mean).^2)/n);
% computation of median
y = sort(x);
% sorts the elements of the array
if mod(n,2) == 1

% n is odd

4. Possible Implementations and Further Comments

32

pos = (n+1)/2;
median = y(pos);
else
% n is even
pos1 = n/2;
pos2 = (n/2)+1;
median = (y(pos1)+y(pos2))/2;
end
% plot of probability density function for x
f = linspace(0,1,n);
% generates vector of length n
% with equidistant entries from 0 to 1
plot(y,f,k*);
hold on;
plot([mean mean],[0,1],r-);
plot([mean+stdev,mean+stdev],[0,1],b-.);
plot([mean-stdev,mean-stdev],[0,1],b-.);
plot(median,0.5,ro,MarkerSize,12);
hold off

Mathematical comments:
The build-in function rand() generates uniformly distributed deviates in the interval
[0, 1] as one can conclude from the probability distribution functions in Fig 4.2. The
bigger the sample, the clearer the distribution function turns out to be a straight line
as well as mean and median coincide.

4.3

If, For, While,


Text Output and Editing Graphics

The internal computations in MATLAB are optimized with respect to efficiency (computational speed) for matrix-vector operations. Hence, it is recommended to program
as much as possible in terms of matrices and vectors, instead of scalars. The scalar
resp. vector programming styles are exemplified in the following implementations.
? stability.m
Scalar programming style:
function stability_s(g,x0,y0,tau)
% stability_s(g,x0,y0,tau)
% determines the stability behavior of the linear system
% A=[-g 1;-1 -g] for given damping parameter g and
% plots the trajectory with respect to the scalar-valued initial
% values x0, y0 and the step size tau

4. Possible Implementations and Further Comments

33

% ==============================================================
% determination of stability
A = [-g, 1; -1, -g];
lambda = eig(A);
maxi = max(real(lambda));
disp( );
disp([Eigenvalues of the system for g=, num2str(g)])
disp(--------------------------------------------)
disp([ lambda_1 = ,num2str(lambda(1))])
disp([ lambda_2 = ,num2str(lambda(2))])
if maxi < 0
disp(=> Asymptotically stable system)
elseif maxi == 0
disp(=> Stable system)
else
disp(=> Instable system)
end
disp(----------------------------------------------)
% determination of trajectories
tstart = 0;
tend = 10;
points = tstart:tau:tend; % grid points
n= length(points);
% number of grid points
x(1) = x0;
% scalar initial values
y(1) = y0;
for i = 2:n
% explict Euler method
x(i) = x(i-1)+tau*(y(i-1)-x(i-1)*g);
y(i) = y(i-1)+tau*(-x(i-1)-y(i-1)*g);
end
plot(x,y,k-,x0,y0,ro);

The function stability s.m computes the trajectory for a single initial tuple (x0,y0).
If one wants to visualize and compare the trajectories of other initial values, the
program must be called several times and the results plotted in the same figure by help
of the commands hold on, hold off. This is an obvious limitation of the program,
since it is time-consuming and circuitous. The vector programming style overcomes
this limitation in stability v.m. Here, the initial values are not read in as scalars
but as row vectors and the computed trajectories are saved in the respective columns
of the matrices x and y.
Vector programming style:
function stability_v(g,x0,y0,tau)

4. Possible Implementations and Further Comments

%
%
%
%
%
%

34

stability_v(g,x0,y0,tau)
determines the stability behavior of the linear system
A=[-g 1;-1 -g] for given damping parameter g and
plots the trajectory with respect to the vector-valued initial
values x0, y0 (row vectors!) and the step size tau
==============================================================

% determination of stability
A = [-g, 1; -1, -g];
lambda = eig(A);
maxi = max(real(lambda));
disp( );
disp([Eigenvalues of the system for g=, num2str(g)])
disp(--------------------------------------------)
disp([ lambda_1 = ,num2str(lambda(1))])
disp([ lambda_2 = ,num2str(lambda(2))])
if maxi < 0
disp(=> Asymptotically stable system)
elseif maxi == 0
disp(=> Stable system)
else
disp(=> Instable system)
end
disp(----------------------------------------------)
% determination of trajectories
tstart = 0;
tend = 10;
points = tstart:tau:tend;
n= length(points);
x(1,:) = x0;
% initial values in row vectors
y(1,:) = y0;
for i = 2:n
% explicit Euler method
x(i,:) = x(i-1,:)+tau*(y(i-1,:)-x(i-1,:)*g);
y(i,:) = y(i-1,:)+tau*(-x(i-1,:)-y(i-1,:)*g);
end
plot(x,y,k-,x0,y0,ro);
% plots x-columns vs y-columns

Extension:
In stability ext.m, the vector-valued initial values for x0, y0 and their trajectories
are combined in a matrix z. This kind of data storage enables matrix-matrix multiplications in the for-loop of the explicit Euler method. Moreover, this function is
more flexible with regard to the input data. It accepts row as well as column vectors
for x0 and y0 and checks if the length of initial vectors fit together. If the input data
is defective, the program terminates with an error message on the screen (command

4. Possible Implementations and Further Comments

35

error()). In addition to this, stability ext.m can be called with either four or six
input parameters. If only four input arguments are used, then tstart=0 and tend=10
by default, otherwise these values are specified by the fifth and sixth argument. Note
that MATLAB saves the number of input arguments automatically in the variable
nargin when calling the function. Finally, the plotting routine is extended in the way
that the figures are titled and the axis are labeled (commands title(), xlabel(),
ylabel()).
Used build-in functions: error(), title(), xlabel(), ylabel(),
nargin (see also nargout)
Advanced vector/matrix programming style:
function stability_ext(g,x0,y0,tau,tstart,tend)
% stability_ext[g,x0,y0,tau,tstart,tend]
% determines the stability behavior of the linear system
% A=[-g 1; -1 g] for given damping parameter g and
% plots the trajectories with respect to the vector-valued
% initial values x0, y0 (any vector) and step size tau
% for the time interval [tstart,tend]
%
% alternatively:
% stability_ext[g,x0,y0,tau]
% then by default: tstart=0; tend=10;
% ========================================================
% determination of stability
A = [-g, 1; -1, -g];
lambda = eig(A);
maxi = max(real(lambda));
disp( );
disp([Eigenvalues of the system for g=, num2str(g)])
disp(------------------------------------------)
disp([ lambda_1 = ,num2str(lambda(1))])
disp([ lambda_2 = ,num2str(lambda(2))])
if maxi < 0
disp(=> Asymptotically stable system)
elseif maxi == 0
disp(=> Stable system)
else
disp(=> Instable system)
end
disp(------------------------------------------)

% determination of trajectories

4. Possible Implementations and Further Comments

if length(x0) ~= length(y0)
% if length of initial values differs,
% then the computation is stopped with an error message
error(Failure! - Check length of initial values!)
end
% check of number of input arguments
if nargin == 4 % if number of input arguments equals 4,
% then define default values for tstart, tend
tstart = 0;
tend = 10;
end
[p,q] = size(x0);
if q == 1 & p ~= 1
x0=x0;
end
[p,q] = size(y0);
if q == 1 & p ~= 1
y0=y0;
end

% provides initial x-values as row vector

% provides initial y-values as row vector

z([1,2],:) = [x0; y0];


% combined initial values
F = eye(2)+tau*A;
% matrix of right-hand side
n = length(tstart:tau:tend);
% number of grid points
for i=2:n
% explicit Euler method
z([2*i-1,2*i],:) = F* z([2*(i-1)-1, 2*(i-1)],:);
end

% plot of trajectories
plot(z([1:2:2*n-1],:),z([2:2:2*n],:),k-,x0,y0,ro);
xlabel(x);
% label of the axes
ylabel(y);
if maxi < 0
% title of the graph
title([Asymptotically stable fixpoint for g= ,num2str(g),...
, tau= ,num2str(tau)]);
elseif maxi == 0
title([Stable fixpoint for g= ,num2str(g),...
, tau= ,num2str(tau)]);
else
title([Instable fixpoint for g= ,num2str(g),...
, tau= ,num2str(tau)]);
end

36

37

4. Possible Implementations and Further Comments


Asymptotically stable fixpoint for g= 1, tau= 0.1

Instable fixpoint for g= 1, tau= 0.1

1.5

5
4

3
2

0.5

1
0
1

0.5

2
3

1.5
1.5

0.5

0
x

0.5

5
5

1.5

0
x

Instable fixpoint for g= 1, tau= 0.001

Asymptotically stable fixpoint for g= 1, tau= 0.001

1.5

4
1

3
2

0.5

1
0
1
0.5

2
3

4
1.5
1.5

0.5

0
x

0.5

1.5

Asymptotically stable fixpoint for g=1


tau=0.1 (dashed), tau=0.001 (solid)

5
5

0
x

Instable fixpoint for g= 1


tau=0.1 (dashed), tau=0.001 (solid)

0
0.5

0.8

1
0.6
1.5
0.4

0.2

2.5
3

0
3.5
0.2

0.4
0.2

0.2

0.4

0.6

0.8

1.2

4.5
0.2

0.4

0.6

0.8

1.2

1.4

1.6

1.8

Figure 4.3: (stability ext.m) Stability behavior of the system. Left: Asymptotically
stable fixpoint (0,0) for g = 1 . Right: Instable fixpoint (0,0) for g = 1 . Trajectories
computed with respect to different step sizes . Top: = 0.1 . Middle: = 0.001 .
Bottom: Comparison of the approximations for an arbitrary trajectory.

38

4. Possible Implementations and Further Comments


Stable fixpoint for g= 0, tau= 0.001

Stable fixpoint for g= 0, tau= 0.1

1.5

2.5
2

1.5
1

0.5

0.5

0.5

0.5

1
1.5

2
2.5
3

0
x

1.5
1.5

0.5

0
x

0.5

1.5

Figure 4.4: (stability ext.m) Analytically stable fixpoint (0,0) for g = 0 , but numerically instable for step size = 0.1 (left), numerically stable for = 0.001 (right).
Mathematical comments:
The explicit Euler method is not A-stable, thus the approximation results depend
on the chosen step size. If the used step size is too large, an analytically stable
fixpoint might be approximated incorrectly as numerically instable as visualized in
Fig 4.4. Hence, to rely on the simulation results, the underlying analytical concept
must be always understood and if possible checked simultaneously. Otherwise, the
numerical outcome might lead to wrong conclusions.
? step size.m
MATLAB distinguishes between script and function files. In script files all variables
are globally defined, in functions only locally. Hence, script files provide all used
variables as output to the workspace, and they cannot be called with certain input
arguments. Function files in contrast write out only the stated output arguments into
the workspace and can be called with and without input arguments as defined in the
file header. It depends on the demands whether a script or a function file is suitable
for a given task. In the following, script files are applied but the use of functions files
are certainly also possible. The command clear in the beginning of the script file
deletes all variables in the workspace.

%
%
%
%
%
%

step_size - script file


computes y, y and y for the linear system
A=[0 1 0; 0 0 1; -1 -1 -1] by help of explicit Euler method
and compares the approximations for different step sizes
with the analytical solution
===========================================================

4. Possible Implementations and Further Comments

clear
% initialization
A = [0 1 0; 0 0 1; -1 -1 -1];
h = [1 0.5 0.25 0.1 0.01 0.001];
xstart = 0;
xend = 2;
z([1,2,3],1) = [0 1 2];

39

% system matrix
% step sizes
% underlying interval
% initial values

% loop over number of step sizes


for j = 1:length(h)
points = xstart:h(j):xend;
% grid points
n = length(points);
% number of grid points
F = eye(3)+h(j)*A;
% matrix of right-hand side
for i = 2:n
z(:,i) = F*z(:,i-1);
end

% explicit Euler method

for k = 1:3
figure(k);
% plots y, y, y in different figures
plot(points,z(k,1:n),k--);
hold on;
end
end
% plot of analytical solutions
x = linspace(xstart,xend,1e6);
figure(1);
plot(x,-cos(x)+2*sin(x)+exp(-x),b-);
title(y -- approximations (dashed), analytical solution (solid))
xlabel(x), ylabel(y)
hold off;
figure(2);
plot(x,sin(x)+2*cos(x)-exp(-x),b-);
title(1st derivative -- approximations (dashed), analytical ...
solution (solid))
xlabel(x), ylabel(y)
hold off
figure(3);
plot(x,cos(x)-2*sin(x)+exp(-x),b-);
title(2nd derivative -- approximations (dashed), analytical ...
solution (solid))
xlabel(x), ylabel(y)
hold off


40

4. Possible Implementations and Further Comments


y approximations (dashed), analytical solution (solid)
4
3.5
3

2.5
2
1.5
1
0.5
0
0

0.5

1
x

1.5

1st derivative approximations (dashed), analytical solution (solid)


3

2.5

1.5

0.5

0.5
0

0.5

1
x

1.5

2nd derivative approximations (dashed), analytical solution (solid)


2

4
0

0.5

1
x

1.5

Figure 4.5: (step size.m) Numerical approximations due to explicit Euler method
converge against analytical solution for decreasing step size.

41

4. Possible Implementations and Further Comments

The plotting routine in step size.m generates three figures for y , y 0 and y 00 respectively, cf. Fig 4.5. Whereas the approximations are visualized as black dashed lines, the
analytical solution is given as blue solid line. For the plot of the analytical solution, a
very fine resolution is produced using the command x=linspace(xstart,xend,1e6).
To distinguish the figures they are titled, and the axes are labeled (command title(),
xlabel(), ylabel()).
Extension:
Instead of three separate figures, one figure with three subwindows is generated by the
command subplot() in step size ext.m. Each subwindow visualizes the solutions of
one function, y , y 0 and y 00 , such that their run is easy to compare, cf. Fig 4.6. For the
plot of the analytical solution, ezplot(function name,[plot start, plot end])
is used. Apart from drawing the function function name over the interval [plot start,
plot end], the command ezplot() gives the graphic the title function name and
labels the x-axis, but it also changes the range of the axes. Hence, the command
axis([xmin,xmax,ymin,ymax]) is applied to zoom into the region of interest. Explanations are included into the graphics at position (xtext,ytext) by means of the
command text(xtext,ytext,explanation).
Used build-in functions: subplot(), ezplot(), axis(), text()
cos(x)+2 sin(x)+exp(x) sin(x)+2 cos(x)exp(x)
4
3
3.5

cos(x)2 sin(x)+exp(x)
2
numerical
analytical

2.5

3
2

2.5
1.5
2

1
1

1.5

2
1

0.5
3

0.5
0
0
0

1
x

1
x

4
0

1
x

Figure 4.6: (step size ext.m) Numerical approximations due to explicit Euler
method converge against analytical solution for decreasing step size.

4. Possible Implementations and Further Comments

%
%
%
%
%
%

step_size_ext - script file


computes y, y and y for the linear system
A=[0 1 0; 0 0 1; -1 -1 -1] by help of explicit Euler method
and compares the approximations for different step sizes
with the analytical solution
===========================================================

clear
% initialization
A = [0 1 0; 0 0 1; -1 -1 -1];
h = [1 0.5 0.25 0.1 0.01 0.001];
xstart = 0;
xend = 2;
z([1,2,3],1) = [0 1 2];

% system matrix
% step sizes
% underlying interval
% initial values

% loop over number of step sizes


for j = 1:length(h)
points = xstart:h(j):xend;
% grid points
n = length(points);
% number of grid points
F = eye(3)+h(j)*A;
% matrix of right-hand side
for i = 2:n
z(:,i) = F*z(:,i-1);
end

% explicit Euler method

for k = 1:3
figure(1)
% plots y, y, y in different partitions of one figure
subplot(1,3,k);
plot(points,z(k,1:n),k--);
hold on;
end
end
% plot of analytical solution
% ezal() gives title and x-label automatically but changes axis
figure(1)
subplot(1,3,1);
ezplot(-cos(x)+2*sin(x)+exp(-x),[xstart,xend]);
axis([0,2,0,4])
% marks the region of interest
hold off;
subplot(1,3,2);
ezplot(sin(x)+2*cos(x)-exp(-x),[xstart,xend]);
axis([0,2,-0.25,3])

42

4. Possible Implementations and Further Comments

43

hold off
subplot(1,3,3);
ezplot(cos(x)-2*sin(x)+exp(-x),[xstart,xend]);
axis([0,2,-4,2])
text(0.75,1.75,numerical --) % places text on the graph
text(0.75,1.25,analytical -)
hold off

Mathematical comments:
In an explicit one-step method the choice of the step size determines the quality of the
numerical approximation. The explicit Euler method is consistent of order p = 1 and
for the given linear system with Lipschitz-continuous right-hand side also convergent
of order p = 1 . Hence the numerical approximations converge towards the analytical
solution for step size h 0 as illustrated in Fig 4.5 / Fig 4.6.
? euler vs rk.m
Scalar programming style:
%
%
%
%
%

euler_vs_rk_s - script file


exemplifies the convergence of the classical RK-method (p=4)
and the explicit Euler method (p=1) on a simple predatorprey model (algorithm in scalar form)
===========================================================

clear
% Butcher scheme for classical RK-method
A = zeros(4,4); A(2,1) = 1/2; A(3,2) = 1/2; A(4,3) = 1;
b = [1 2 2 1]/6;
c = [0 1 1 2]/2;
% parameters of model
alpha = 1/4;
beta = -1/100;
gamma = -1;
delta = 1/100;
% initialization
tstart = 0;
tend = 20;
xRK(1) = 80;
yRK(1) = 30;
xE(1) = xRK(1);
yE(1) = yRK(1);

% scalar-valued initial values

4. Possible Implementations and Further Comments

44

h = [1,0.5,0.1,0.01];
% step sizes
lh = length(h);
for m = 1:lh
t = tstart:h(m):tend;
lt = length(t);
% computation of approximations for respective step size
% in scalar form
for i = 2:lt;
% Runge-Kutta Method
xnew = xRK(i-1);
ynew = yRK(i-1);
kx(1) = (alpha+beta*ynew)*xnew;
ky(1) = (gamma+delta*xnew)*ynew;
for j=2:length(b);
xnew = xRK(i-1) + h(m)*kx(1:j-1)*A(j,1:j-1);
ynew = yRK(i-1) + h(m)*ky(1:j-1)*A(j,1:j-1);
kx(j) = (alpha+beta*ynew)*xnew;
ky(j) = (gamma+delta*xnew)*ynew;
end
xRK(i) = xRK(i-1)+h(m)*kx*b;
yRK(i) = yRK(i-1)+h(m)*ky*b;
% Explicit Euler
xE(i) = xE(i-1)+h(m)*((alpha+beta*yE(i-1))*xE(i-1));
yE(i) = yE(i-1)+h(m)*((gamma+delta*xE(i-1))*yE(i-1));
end
% plotting and labeling of graphics
subplot(round(lh/2),2,m);
plot(xRK(1:lt),yRK(1:lt),r-,xE(1:lt),yE(1:lt),k-.);
hold on
axis([10,170,0,95]);
% sets ranges of axes
title([h = , num2str(h(m))]);
% gives title
if m == 2 legend(RK,Euler); end % creates legend
hold off
end

Vector programming style:
%
%
%
%
%

euler_vs_rk_v - script file


exemplifies the convergence of the classical RK-method (p=4)
and the explicit Euler method (p=1) on a simple predatorprey model (algorithm in vector form)
===========================================================

clear

4. Possible Implementations and Further Comments

%
A
b
c

Butcher scheme for classical RK-method


= zeros(4,4); A(2,1) = 1/2; A(3,2) = 1/2; A(4,3) = 1;
= [1 2 2 1]/6;
= [0 1 1 2]/2;

% parameters of model
alpha = 1/4;
beta = -1/100;
gamma = -1;
delta = 1/100;
% initialization as system
tstart = 0;
tend = 20;
zRK(:,1) = [80 30];
% vector-valued initial values
zE(:,1) = zRK(:,1);
h = [1,0.5,0.1,0.01];
% step sizes
lh = length(h);
for m = 1:lh
t = tstart:h(m):tend;
lt = length(t);
% computation of approximations for respective step size
% in vector form
for i = 2:lt;
% Runge-Kutta Method
znew = zRK(:,i-1);
k(:,1) = [alpha+beta*znew(2); gamma+delta*znew(1)].*znew;
for j=2:length(b);
znew = zRK(:,i-1) + h(m)*k(:,1:j-1)*A(j,1:j-1);
k(:,j) = [alpha+beta*znew(2); gamma+delta*znew(1)].*znew;
end
zRK(:,i) = zRK(:,i-1)+h(m)*k*b;
% Explicit Euler
zE(:,i) = zE(:,i-1)+h(m)*[alpha+beta*zE(2,i-1); gamma+ ...
delta*zE(1,i-1)].*zE(:,i-1);
end
% plotting and labeling of graphics
subplot(round(lh/2),2,m);
plot(zRK(1,1:lt),zRK(2,1:lt),r-,zE(1,1:lt),zE(2,1:lt),k-.);
hold on
axis([10,170,0,95]);
% sets ranges of axes
title([h = , num2str(h(m))]);
% gives title
if m == 2 legend(RK,Euler); end % creates legend
hold off
end

45

46

4. Possible Implementations and Further Comments


h=1

h = 0.5

80

80

60

60

40

40

20

20

50

100

150

h = 0.1

0
RK
Euler
80

60

60

40

40

20

20
50

100

100

150

h = 0.01

80

50

150

50

100

150

Figure 4.7: (euler vs rk ?.m) Comparison of explicit Euler and classical RKapproximations for different step sizes h .
All script files euler vs rk ?.m place the legend in the second subwindow in the first
row according to the if-condition around the legend() command. To change its
position like in Fig 4.7, one must click on the legend with the right mouse-button,
mark it and pull it at the favored place in the figure.
Extension:
The script files euler vs rk s.m and euler vs rk v.m are especially written for the
given predator-prey model of the task. In contrast, the RungeKutta and Euler
method in euler vs rk ext.m can cope with variable models, since the predator-prey
model is defined independently in the separate function file f pp.m which is called by
euler vs rk ext.m and easy to modify and to adopt to other models. Calling other
functions enables more flexibility and clearness in the program, but the price one often
has to pay for it is the slowing down of the computation.

% euler_vs_rk_ext - script file


% -> calls function out = f_pp(in), in, out: column vectors
% exemplifies the convergence of the classical RK-method (p=4)

4. Possible Implementations and Further Comments

47

% and the explicit Euler method (p=1) for a variable predator% prey model defined as system in the function f_pp.m
% ===========================================================
clear
% Butcher scheme for classical RK-method
A = zeros(4,4); A(2,1) = 1/2; A(3,2) = 1/2; A(4,3) = 1;
b = [1 2 2 1]/6;
c = [0 1 1 2]/2;
% initialization as system
tstart = 0;
tend = 20;
zRK(:,1) = [80 30];
% vector-valued initial values
zE(:,1) = zRK(:,1);
h = [1,0.5,0.1,0.01];
% step sizes
lh = length(h);
for m = 1:lh
t = tstart:h(m):tend;
lt = length(t);
% computation of approximations for respective step size
% with variable model in system (vector) form
for i = 2:lt;
% Runge-Kutta Method
k(:,1) = f_pp(zRK(:,i-1));
for j=2:length(b);
k(:,j) = f_pp(zRK(:,i-1)+h(m)*k(:,1:j-1)*A(j,1:j-1));
end
zRK(:,i) = zRK(:,i-1)+h(m)*k*b;
% Explicit Euler
zE(:,i) = zE(:,i-1)+h(m)*f_pp(zE(:,i-1));
end
% plotting and labeling of graphics
subplot(round(lh/2),2,m);
plot(zRK(1,1:lt),zRK(2,1:lt),r-,zE(1,1:lt),zE(2,1:lt),k-.);
hold on
axis([10,170,0,95]);
% sets ranges of axes
title([h = , num2str(h(m))]);
% gives title
if m == 2 legend(RK,Euler); end % creates legend
hold off
end

=========================================
function w = f_pp(v)

4. Possible Implementations and Further Comments

48

% w = f_pp(v)
% defines predator-prey model with column vectors v, w
% ====================================================
alpha = 1/4;
beta = -1/100;
gamma = -1;
delta = 1/100;
w = [alpha+beta*v(2); gamma+delta*v(1)].*v;

Mathematical comments:
The explicit Euler method is of consistence/convergence order p = 1 , the classical
RungeKutta method of order p = 4 . The consequences of this difference can be seen
in Fig 4.7. The RungeKutta method yields the correct approximation already for a
relatively large step size, i.e. h = 1 , whereas the Euler method requires a step size of
h = 0.01 for the same result. Hence, the Euler method needs 100 steps instead of 1
in the RungeKutta method to provide the same accuracy. Comparing the operations
performed in one step, the RungeKutta method is obviously more costly due to the
calculations of the different levels ki , i = 1, ..., 4 , but definitely not as costly as 100
simple Euler steps. Consequently, the practical use of the higher-order RungeKutta
method is advisable.
? search.m

function flag = search_binary(x,v)


% flag = search_binary(x,v)
% determines whether or not the value x is contained in the
% vector v by help of a binary search
% flag = 1, if x is in v, otherwise flag = 0
% ===========================================================
flag = 0;
w = sort(v);
n = length(w);

% initialization of flag as x not found

% division-loop of w
% as long as x-value has not been found and w has components
while (n > 0) & (flag == 0)
if mod(n,2) == 1
% determination of middle point position
mid = (n+1)/2;
else
mid = n/2;
end

4. Possible Implementations and Further Comments

if x == w(mid)
flag = 1;
elseif x < w(mid)
w = w(1:mid-1);
else % x > w(mid)
w = w(mid+1:n);
end

% check of x and middle point


% x-value found
% otherwise partition of w

n = length(w);

% update of length

49

end

The binary search algorithm is an every elegant and efficient way to search for an element in a given vector without applying any fancy MATLAB build-in functions. It is
exclusively based on the recursive division of the given vector which can be straightforward implemented by a while-loop. However, using build-in functions, in particular
logical operators, a search routine could look like exemplified in search matlab.m and
search matlab2.m.
Used build-in functions: Logical operators
x == v: returns a binary vector of ones and zeros,
1 for true (i.e. x == v(i)) , 0 for false
analogously for all other comparisons, e.g. =, >=, <=, >, <
any(): returns 1 if any element is non-zero, 0 otherwise
all(): returns 1 if all elements are non-zero, 0 otherwise

any(),

all(): returns the binary opposite of any() resp. all()

additionally see
find(): returns the indices of non-zero elements. It can be used in combination
with logical operators.
Example: x =[2 10 0 0 3 -1]; find(x) = ans = [1 2 5 6]
find(x > 2) = ans = [2 5]

function [flag, number] = search_matlab(x,v)


% [flag, number] = search_matlab(x,v)
% determines whether or not the value x is contained in the
% vector v by help of MATLAB build-in functions
% flag = 1, if x is in v, otherwise flag = 0
% number particularly specifies how often x is contained in v
% ===========================================================
compare = (x==v);

% if x equals the component v(i)


% the component compare(i) is 1, else 0

4. Possible Implementations and Further Comments

50

number = sum(compare);
flag = any(number);
% any() returns 1 if its argument is
% non-zero, else 0


function flag = search_matlab2(x,v)


% flag = search_matlab2(x,v)
% determines whether or not the value x is contained in the
% vector v by help of MATLAB build-in functions
% flag = 1, if x is in v, otherwise flag = 0
% ===========================================================
flag = ~all(v-x);
% all() returns 1 if all arguments are non-zero, else 0
% the logical operator not ~ returns the binary opposite,
% e.g. ~1 = 0, ~0 = 1

As alternative to the MATLAB build-in function sort(), the function mysort.m exemplifies a sorting algorithm that is based on the idea of the binary recursions, see
search binary.m.

function s = mysort(x);
% s = mysort(x)
% sorts the components of vector x by help of a binary
% algorithm and returns them in the same-sized vector s
% =====================================================
[p,q] = size(x);
n = p*q;
s = x(1);
for i = n:-1:2;
% initialization
x = x(2:i);
xc = x(1);
w = s;
m = length(w);
pos = 1;
flag = 0;

% default position of xc in sorted s

% loop for finding the correct position of xc: binary search


while (flag == 0) & (m > 0)
mid = round(m/2);

4. Possible Implementations and Further Comments

51

if xc < w(mid)
% no update of position
w = w(1:mid-1);
elseif xc > w(mid) % update
pos = pos + mid;
w = w(mid+1:m);
else
% update
pos = pos + mid;
flag = 1;
end
m = length(w);
end
% assembly of s
s = [s(1:pos-1) xc s(pos:n-i+1)];
end
if (q==1) & (p~=1)
s=s;
end

% return of same-sized s as x


4.4

ODE-Solvers and Efficiency of Algorithms

? implicit.m

function implicit
% implicit
% solves the Van-der-Pol equations by help of the implicit
% center point rule for parameter mu = 10; initial value [2;0],
% time interval [0,20], stepsize h = 1e-3 and
% iteration error tolerance tol = 1e-8
% and plots the orbit and the number of iteration required
% in the Newton method
% ============================================================
% initialization
mu = 10;
h = 1e-3;
tpoints = 0:h:20;
z(:,1) = [2;0];
tol = 1e-8;
% measuring elapsed time and number of operations
% flops(0), tic

4. Possible Implementations and Further Comments

52

% implicit center point rule


for i = 2:length(tpoints)
znew = z(:,i-1);
diff = 1;
iter(i-1) = 0;
% counter for iterations
while diff > tol
% Newton iteration
zold = znew;
mid = (zold + z(:,i-1))/2; % center point
% right-hand side F
F = zold-z(:,i-1)-h*[mid(2); mu*(1-mid(1)^2)*mid(2)-mid(1)];
% Jacobian matrix
DF = eye(2)-h/2*[0, 1; -2*mu*mid(1)*mid(2)-1, mu*(1-mid(1)^2)];
% analytical inverse
% inverse = [DF(2,2), -DF(1,2); -DF(2,1), DF(1,1)]/det(DF);
% update
znew = zold - DF\F;
% znew = zold - inverse*F;
diff = norm(znew-zold,2); % Euclidian norm
% 2.argument specifies the norm
iter(i-1)=iter(i-1)+1;
end
z(:,i) = znew;
% storing of found new value
end
% toc, flops
figure
plot(z(1,:),z(2,:),k-,z(1,1),z(2,1),ro);
xlabel(x), ylabel(y)
title([Van-der-Pol Equation, \mu=,num2str(mu)]);
legend(orbit,initial point,4)
figure
stepnumber = 1:length(tpoints)-1;
plot(stepnumber,iter,k*);
xlabel(time steps), ylabel(iteration steps)
title(Iteration steps in Newton method)

Extension:
The function implicit.m solves the Van-der-Pol equations for fixed parameters by
help of the implicit Center-point rule and meets therefore the demands of the exercise
task. The extension implicit ext.m in combination with vdp.m goes a step further.
In implicit ext.m, a general ODE-solver based on the implicit Center-point rule is
realized. The Van-der-Pol equations and their related variable parameters are stored
independently in the ODE-file vdp.m. Apart from the derivative, vdp.m might provide
the initial values including options (like error tolerances, step size control etc.) and

4. Possible Implementations and Further Comments

53

the Jacobian matrix by using the switch command for varying flag inputs. Style and
structure of vdp.m is typical for MATLAB ODE-files such that every build-in solver
can handle vdp.m, e.g. call the stiff solver
[t,z] = ode23s(vdp,[tstart,tfinal],[z10;z20],[],mu).
The fourth argument is reserved for options that can be set with odeset or left with
the default values. Alternatively,
[t,z] = ode23s(vdp,[],[],[],mu),
then time interval, initial conditions and options are taken from the init routine of
the ODE-file.
Used build-in functions:
ODE-solvers: ode23s, ode15s, ode23t, ode23tb
(see also help odefile, help odeset)
switch, case, otherwise: comparable to if, elseif, else but for text strings

function implicit_ext(mu,tspan,z0,h,tol)
% implicit_ext(mu,tspan,z0,h,tol)
% determines the solution of the Van-der-Pol equations
% by help of the implicit center point rule and plots it
% for parameter mu, time interval [tspan(1),tspan(2)]
% initial values [z0(1),z0(2)], step size h and
% iteration error tolerance tol
%
% alternatively implicit_ext(mu)
% then [tspan,z0,h,tol] = vdp([],[],initial,[]);
% alternatively implicit_ext
% then additionally mu = 10 by default
%
% vdp() is a typical ODE-file
% =========================================================
% initialization
if nargin == 0
mu = 10;
end
if nargin <= 1
[tspan,z0,h,tol] = vdp([],[],initial,[]);
end
z(:,1) = z0;
tpoints=tspan(1):h:tspan(2);
% implicit center point rule
for i = 2:length(tpoints)
znew = z(:,i-1);

4. Possible Implementations and Further Comments

54

diff = 1;
while diff > tol
% Newton method
zold = znew;
mid = (zold + z(:,i-1))/2;
F = zold-z(:,i-1)-h*vdp([],mid,,mu);
DF = eye(2)-h/2*vdp([],mid,jacobian,mu);
znew = zold - DF\F;
diff = norm(znew-zold);
end
z(:,i) = znew;
end
% plotting and labeling
figure
plot(tpoints,z(1,:),k-,tpoints,z(2,:),k-.);
xlabel(t)
title([Van-der-Pol Equation, \mu=,num2str(mu)]);
legend(z_1,z_2,2)
figure
plot(z(1,:),z(2,:),k-,z(1,1),z(2,1),ro,0,0,b*);
xlabel(z_1), ylabel(z_2)
title([Van-der-Pol Equation, \mu=,num2str(mu)]);
legend(orbit,initial point,fixpoint,4)

==========================================
function varargout = vdp(t,y,flag,p1)
% ODE-file
% varargout = vdp(t,y,flag,p1) provides the Van-der-Pol Equations
% ===============================================================
switch flag
case
% Return
varargout{1} = f(t,y,p1);
case init
% Return
[varargout{1:3}] = init;
case jacobian
% Return
varargout{1} = jacobian(t,y,p1);
case initial
% Return
[varargout{1:4}] = initial;
otherwise
error([Unknown flag flag .]);
end

dy/dt = f(t,y).
[tspan,y0,options].
Jacobian matrix df/dy.
[tspan,y0,step,tol].

% ------------------------------------------------------------

55

4. Possible Implementations and Further Comments

function dydt = f(t,y,p1)


dydt = [y(2); p1*(1-y(1)^2)*y(2)-y(1)];
% -----------------------------------------------------------function [tspan,y0,options] = init
tspan = [0 20];
y0 = [2; 0];
options = [];
% options = odeset(RelTol,1e-8,AbsTol,1e-8,jacobian,on,...
%
Vectorized,on,MaxStep,1e-3,NormControl,on);
% -----------------------------------------------------------function dfdy = jacobian(t,y,p1)
dfdy = [0, 1; -2*p1*y(1)*y(2)-1,

p1*(1-y(1)^2)];

% -----------------------------------------------------------function [tspan,y0,step,tol] = initial


tspan = [0 20];
y0 = [2; 0];
step = 1e-3;
tol = 1e-6;

VanderPol Equation, =10

VanderPol Equation, =10

15

15
z1
z
2

10

10

10

10

15
0

10
t

15

20

15
3

orbit
initial point
fixpoint
2

z1

Figure 4.8: (implicit ext.m) Van-der-Pol equations for = 10 . Left: components


z1 , z2 over time t . Right: trajectory.
Mathematical and algorithmic comments:
The Center-point rule is an implicit one-step method that requires the solving of a nonlinear system of equations in every time step. In comparison to the explicit methods,
it is A-stable such that its performance is not restricted by the choice of the step size.

56

4. Possible Implementations and Further Comments


Iteration steps in Newton method

iteration steps

1
0

0.5

1
time steps

1.5

2
4

x 10

Figure 4.9: (implicit.m) Iteration steps in Newton method for tol=1e-8.


Error Tolerance
108
103

Numerical Jacobian
Analytical Jacobian
CPU-time (sec) # flops
CPU-time (sec) # flops
25.28
3 839 862
23.57
1 608 663
22.73
2 056 484
22.77
1 460 723

Table 1: (implicit.m) Number of operations and computation time for solving the
Van-der-Pol equations by means of the Center-point rule with the values of the exercise
task, in particular step size h = 103 .
However, the effort of the method depends on the desired accuracy of the Newton
iteration, since the number of iteration steps performed in the Newton algorithm is
determined by the set error tolerance. To reach a high accuracy of tol=1e-8, two steps
are generally required per time step, cf. Fig 4.9. For a rougher approximation with
tol=1e-3, the number of steps halves and the needed computation time is speeded up.
To get a better feeling how the choice of the error tolerance and the determination of
the Jacobian matrix in the Newton method affects the number of operations (# flops)
and the CPU-time, study the overview in Tab 1. Providing the Jacobian analytically
reduces the number of function evaluations drastically but has hardly any influence
on the elapsed time. Instead, the CPU-time is dominated by the step size h which
ODE-solver
ode23s
ode15s
ode23t
ode23tb
implicit
implicit ext

Error Tolerance
RelTol AbsTol
103
106
k
k
k
k
k
k

106

106

Step Size
maximal
2 (adaptive)
k
k
k
0.1 (fixed)
0.1 (fixed)

CPU-time
0.25
0.27
0.30
0.30
2.50
6.00

#flops
48
72
57
58
500
500

210
255
260
266
000
000

Table 2: (vdm.m) Number of operations and computation time for solving the Vander-Pol equations with default options for the solvers and numerical Jacobian.

4. Possible Implementations and Further Comments

57

can be concluded from Tab 2. The MATLAB build-in ODE-solvers have the great
advantage of using an adaptive step size control such that they approximate the Vander-Pol equations with fewer steps and hence faster than implicit?.m regarding the
same error tolerances. They are undoubtedly more efficient.
The quantities number of operations and elapsed CPU-time measuring the quality /
efficiency of an algorithm are (mainly) independent as it can be clearly seen in this
example. The functions implicit.m and implicit ext.m perform approximately the
same number of evaluations, but the function calls of vdp.m in implicit ext.m slow
the calculations down.
From the mathematical point of view, a implicit algorithm might sometimes be slower
than an explicit one although using bigger step sizes and thus less steps for the integration of the ODE. In such a case, the effort of solving the complex non-linear system
in one step is higher than the one for computing several simple explicit steps instead.

4.5

Matrix Manipulations, Sparse Matrices and 3D-Plots

? fd.m

function fd(problem)
% fd(problem)
% computes the solution of the 2D Poisson equation with
% Dirichlet conditions for
% problem = 1: f=1, g=0
% problem = 2: f=0, g=x^2
% by help of the finite difference method on a regular grid
%
% anyhow, the function is implemented to handle also irregular
% grids by providing step sizes in x and y-directions (h and k)
% ===============================================================
%
h
k
x
y
m
n
p

initialization
= 1/25;
= h;
= 0:h:1;
= 0:k:1;
= length(x);
= length(y);
= m*n;

L = zeros(p,p);
u = zeros(p,1);
f = zeros(p,1);

4. Possible Implementations and Further Comments

% general 5-point Laplacian stencil for different h and k


stencil = [-1/k^2, zeros(1,m-2), -1/h^2, 2/h^2+2/k^2, ...
-1/h^2, zeros(1,m-2), -1/k^2];
% assembly of L
% boundary values
%
lower
L(1:m,1:m) = eye(m);
%
upper
L(p-m+1:p,p-m+1:p) = eye(m);
%
left and right
for j=2:n-1
L([(j-1)*m+1,j*m],[(j-1)*m+1,j*m]) = eye(2);
end
% inner values
for i = 2:m-1
for j = 2:(n-1)
L((j-1)*m+i,[(j-2)*m+i:j*m+i]) = stencil;
end
end
% assembly of f
if problem == 1
% inner values
for i = 2:m-1
f([1:(n-2)]*m+i) = ones(n-2,1);
end
else %problem == 2
% boundary values
f(1:m)
= x.^2; % lower
f(p-m+1:p) = x.^2; % upper
f([1:(n-2)]*m+1) = x(1)^2*ones(n-2,1); % left
f([2:(n-1)]*m)
= x(m)^2*ones(n-2,1); % right
end
% solution
u = L\f;
% plotting
for j = 1:n
% rewriting u in grid format
U(j,:) = u((j-1)*m+1:j*m);
end
[X,Y] = meshgrid(x,y);
% generation of grid
surf(X,Y,U)
% surface plot
xlabel(x), ylabel(y), zlabel(u);
title([Solution of Poisson Problem ,num2str(problem), ...

58

59

4. Possible Implementations and Further Comments


Solution of Poisson Problem 1 for step sizes h=0.04, k=0.04

Solution of Poisson Problem 2 for step sizes h=0.04, k=0.04

0.08

1.5

0.06

0.04
0.5

0.02
0

0
0.02
1

0.5
1

1
0.8

0.5

0.6

1
0.8

0.5

0.6

0.4
y

0.4

0.2
0

0.2
0

Figure 4.10: (fd.m) Poisson equation on regular grid, h = k = 0.04 , for Problem 1
(left), Problem 2 (right).
for step sizes h=, num2str(h), , k=, num2str(k)])

Extension:
The function file fd.m solves the elliptic Dirichlet boundary value problems 1 and
2 on a regular grid with h = k = 4 102 , cf. Fig 4.10. By defining step sizes h
and k in x and y -direction it is already designed to handle also irregular grids with
constant mesh. However, initializing smaller step sizes, e.g. h 102 , k 102 ,
the performance of fd.m causes memory problems in MATLAB and is terminated.
Since the step size is anti-proportional to the number of grid points in the respective
directions, i.e. m = h1 +1 , n = k 1 +1 , small step sizes imply fine resolution and lots
of grid points (in total: p = m n ). Hence, the finite difference matrix Lh,k is of size
p p . In fd.m the command L = zeros(p,p) requires the storage of all components.
Taking h = k = 102 yields # components = 10 8 of which maximal 5p = 5 104 are
non-zero due to the applied 5-point difference stencil. Half of the information to be
stored is zero and thus redundant.
Sparse Matrix Computations:
MATLAB has a special storage mode to deal with this kind of large, sparse matrices.
Instead of storing all components in the default full mode, it saves only the non-zero
entries in the sparse mode. This leads to a drastical reduction of memory demands and
to the avoidance of arithmetic operations on zero entries. Thus, the efficiency in storage
and time is increased which makes feasible the solution of significantly larger problems
than would otherwise be possible. The sparse mode can be incooperated in fd.m by
the modification of a single line. The command L = zeros(p,p) must be replaced by
L = spalloc(p,p,5*p)
that creates a sparse zero matrix of size p p with maximal 5p non-zero entries.
The third argument in spalloc() allocates the required space in memory and should
therefore never be underestimated. Sparse matrices are stored as linear arrays of their
non-zero elements along with their row and column indices, but can be handled in
the same way as full matrices, since algorithmic operations and (most) MATLAB
build-in functions work independently of the storage mode. The functions full() and

60

4. Possible Implementations and Further Comments

sparse() convert between the two modes. Operations on matrices in sparse (S) and
full mode (F) yield the following results:
Full:
Full:
Sparse:

S+F
S+S

operations on full matrices


S*F S\F
F\S
S*S S.*S S.*F S n S. n

S\S

The sparse analogs of eye, zeros, ones, randn and diag for full matrices are, respectively
speye, sparse, spones, sprandn, spdiags
.
The versatile function sparse() creates not only a sparse zero matrix of size m n
by sparse(m,n) or converts the full matrix F into a sparse one by sparse(F), but
also permits the generation of a sparse matrix via listing its non-zero elements. Take
for example:
row index = [1 2 3 4 4]; col index = [1 2 3 1 2]; entry = [5 6 7 8 9];
S = sparse(row index,col index,entry,m,n); full(S)
Used build-in function: spdiags()
Example: n = 1e4; d = ones(n,1); e = [1:n]; f = e;
T = spdiags([e,d,f],[-3,0,2],n,n)
creates a tridiagonal matrix of size n n with the column vector e on the third lower
subdiagonal, d on the main diagonal and f on the second upper subdiagonal. Note
that the first 3 elements of e and the last 2 of f are missing in the diagonals of T.
Add-on:
To get a feeling for the efficiency and power of the sparse storage mode, solve the
following tridiagonal system of equations stemming from a second difference approximation in a finite difference method for n = 20, 50, 100, 500, 1000 :
e = ones(n,1); d = -2*e; T = spdiags([e,d,e],[-1,0,1],n,n); A = full(T);
b = ones(n,1); s = sparse(b);
tic, T \ s; sparsetime=toc, tic, A \ b; fulltime=toc,
Coming back to the finite difference approximation of the 2D Poisson equation, in the
extended version fd ext.m the Dirichlet boundary values problems are solved on a fine
irregular grid with varying step sizes hi , kj . Hereby, the sparse difference matrix is
assembled using the command spdiags().

function [X,Y,U]=fd_ext(problem,h,k)
% [X,Y,U] = fd_ext(problem,h,k)
% computes the solution of the 2D Poisson equation with
% Dirichlet conditions for
% problem = 1: f=1, g=0
% problem = 2: f=0, g=x^2
% by help of the finite difference method on a irregular grid
% for step sizes h in x and k in y-direction
%

4. Possible Implementations and Further Comments

% finite difference matrix is implemented as sparse matrix


% ===============================================================
% initialization
if nargin == 1
h = 1/25;
k = h;
end
% grid generation
lh = length(h);
lk = length(k);
if lh == 1
x = 0:h:1;
else
x(1) = 0;
for i=1:lh
x(i+1) = x(i)+h(i);
end
end
if lk == 1
y = 0:k:1;
else
y(1) = 0;
for j=1:lk
y(j+1) = y(j)+k(j);
end
end
m = length(x);
n = length(y);
p = m*n;
u = zeros(p,1);
f = zeros(p,1);
% assembly of L as sparse matrix with 5 non-zero diagonals
if lh == 1 & lk == 1
center = repmat([1, (2/h^2+2/k^2)*ones(1,m-2), 1],1,n-2);
center = [ones(1,m), center, ones(1,m)];
horizontal = repmat([0, -1/h^2*ones(1,m-2), 0],1,n-2);
left = [zeros(1,m), horizontal, zeros(1,m)];
right = left;
vertical = repmat([0, -1/k^2*ones(1,m-2), 0],1,n-2);
down = [zeros(1,m), vertical, zeros(1,m)];
up = down;

61

4. Possible Implementations and Further Comments

elseif lh == 1;
horizontal = repmat([0, -1/h^2*ones(1,m-2), 0],1,n-2);
left = [zeros(1,m), horizontal, zeros(1,m)];
right = left;
hcenter = repmat([1, (2/h^2)*ones(1,m-2), 1],1,n-2);
kcenter = sparse(p,1);
down = sparse(p,1);
up = sparse(p,1);
for j = 2:n-1
kcenter((j-1)*m+[2:m-1])=[(2/(k(j-1)*k(j)))*ones(m-2,1)];
down((j-1)*m+[2:m-1])= [-2/((k(j-1)+k(j))*k(j-1))*ones(m-2,1)];
up((j-1)*m+[2:m-1])= [-2/((k(j-1)+k(j))*k(j))*ones(m-2,1)];
end
center = [ones(1,m), hcenter, ones(1,m)]+ kcenter;
elseif lk == 1;
vertical = repmat([0, -1/k^2*ones(1,m-2), 0],1,n-2);
down = [zeros(1,m), vertical, zeros(1,m)];
up = down;
kcenter = repmat([1, (2/k^2)*ones(1,m-2), 1],1,n-2);
hcenter = sparse(p,1);
left = sparse(p,1);
right = sparse(p,1);
for i = 2:m-1
hcenter([1:n-2]*m+i)=[(2/(h(i-1)*h(i)))*ones(1,n-2)];
left([1:n-2]*m+i)= [-2/((h(i-1)+h(i))*h(i-1))*ones(1,n-2)];
right([1:n-2]*m+i)= [-2/((h(i-1)+h(i))*h(i))*ones(1,n-2)];
end
center = [ones(1,m), kcenter, ones(1,m)]+ hcenter;
else
hcenter = sparse(p,1);
kcenter = sparse(p,1);
left = sparse(p,1);
right = sparse(p,1);
down = sparse(p,1);
up = sparse(p,1);
for i = 2:m-1
hcenter([1:n-2]*m+i)=[(2/(h(i-1)*h(i)))*ones(1,n-2)];
left([1:n-2]*m+i)= [-2/((h(i-1)+h(i))*h(i-1))*ones(1,n-2)];
right([1:n-2]*m+i)= [-2/((h(i-1)+h(i))*h(i))*ones(1,n-2)];
end
for j = 2:n-1
kcenter((j-1)*m+[1:m])=[1; (2/(k(j-1)*k(j)))*ones(m-2,1); 1];
down((j-1)*m+[2:m-1])= [-2/((k(j-1)+k(j))*k(j-1))*ones(m-2,1)];
up((j-1)*m+[2:m-1])= [-2/((k(j-1)+k(j))*k(j))*ones(m-2,1)];
end
center = hcenter+kcenter;

62

4. Possible Implementations and Further Comments

63

center([1:m,p-m+1:p]) = ones(2*m,1);
end
L = spdiags([up, right, center, left, down], [-m,-1,0,1,m], p, p);
% assembly of f
if problem == 1
% inner values
for i = 2:m-1
f([1:(n-2)]*m+i) = ones(n-2,1);
end
else % problem == 2
% boundary values
f(1:m)
= x.^2; % lower
f(p-m+1:p) = x.^2; % upper
f([1:(n-2)]*m+1) = x(1)^2*ones(n-2,1); % left
f([2:(n-1)]*m)
= x(m)^2*ones(n-2,1); % right
end
% solution
u = L\f;
% plotting
U = reshape(u,m,n);
% rewriting u in grid format
[X,Y] = meshgrid(x,y);
% generation of grid
surf(X,Y,U);
% surface plot
xlabel(x), ylabel(y), zlabel(u);
if (lh == 1) & (lk == 1)
title([Solution of Poisson Problem ,num2str(problem), ...
for constant step sizes h=, num2str(h), , k=, num2str(k)])
else
title([Solution of Poisson Problem ,num2str(problem), ...
for varying step sizes])
end

Mathematical comments:
The use of irregular grids often improves the approximation quality of finite difference
methods, since it enables the finer resolution of critical domains of special interest. In
contrast, regions where the solution does not vary much can be discretized roughly
which saves memory storage and reduces the CPU-time. Irregular grids are known as
adaptive meshes (cf. Fig 4.11). Irregular grids changing over time are under the topic
adaptive mesh refinement a very popular field of recent research since its reasonable
application is necessary for efficient and accurate numerical simulations of most reallife problems, e.g. blowing up of air-bags, filling of car petrol tanks, manufacturing of
glass.

64

4. Possible Implementations and Further Comments


Solution of Poisson Problem 1
for constant step sizes h=0.01, k=0.01

Solution of Poisson Problem 2


for constant step sizes h=0.01, k=0.01

0.08

1.5

0.06

0.04
0.5

0.02
0

0
0.02
1

0.5
1

0.8

0.5

0.8

0.5

0.6

0.6

0.4
y

0.4

0.2
0

0.2
0

Solution of Poisson Problem 2 for varying step sizes

Solution of Poisson Problem 1 for varying step sizes

1.5

0.08
0.06

0.04
0.5

0.02
0

0.5
1

0.02
1

1
0.8

0.5

0.6

0.8

0.5

0.6
0.4

0.4
y

0.2
0

0.2
0

Figure 4.11: (fd ext.m) Poisson equation on fine regular, h = k = 102 , (top) and
irregular grid (bottom) for Problem 1 (left), Problem 2 (right).

4.6

Nargin, Switch, Polynomial Functions and


M-File Management

? random walk.m

function [mean_n,mean_a,error] = random_walk(P0,p,u,d,t,n)


% [mean_n,mean_a,error] = random_walk(P0,p,u,d,t,n)
% simulates a random walk and computes its numerical mean_n at
% at time t by using n Monte-Carlo simulations with respect to
% starting value P0, probability p and increments u and d and
% compares it with the analytical mean mean_a by plotting the
% probability distribution function and determing the error
%
% alternatively: [mean_n,mean_a,error] = random_walk(P0)
% then by default: n=100, t=100; u=d=10; p=0.5
%
% alternatively: [mean_n,mean_a,error] = random_walk(P0,p,u,d)

4. Possible Implementations and Further Comments

65

% then by default: n=100, t=100


% ================================================================
% check of number of input arguments
if nargin == 1
t = 100;
n = 100;
u = 10;
d = u;
p = 0.5;
elseif nargin == 4
t = 100;
n = 100;
end
% Monte-Carlo Simulation
Pt = P0*ones(1,n);
for j=1:n
for i=1:t
r=rand(1);
if r<=p
Pt(j)=Pt(j)+u;
else
Pt(j)=Pt(j)-d;
end
end
end

% random walk

% computation of means
mean_a = P0+t*((u+d)*p-d); % analytical
mean_n = sum(Pt)/n;
% numerical
error = abs(mean_a-mean_n);
% plot of probability distribution function
Pt = sort(Pt);
distribution = linspace(0,1,n);
plot(Pt,distribution,k*,MarkerSize,6)
hold on
plot([mean_n, mean_n],[0,1],b--,LineWidth,2)
plot([mean_a, mean_a],[0,1],r-,LineWidth,2)
title([Probability density distribution of random walk: P0=...
,num2str(P0),, p=,num2str(p),, u=,num2str(u),...
, d=,num2str(d),, t=,num2str(t)])
legend(observables,mean (monte carlo),mean (analytical),2)
hold off


66

4. Possible Implementations and Further Comments


Probability density distribution of random walk:
P0=0, p=0.5, u=10, d=10, t=100

Probability density distribution of random walk:


P0=0, p=0.5, u=10, d=10, t=100

1
0.9

1
observables
mean (monte carlo)
mean (analytical)

0.8

0.8

0.7

0.7

0.6

0.6

0.5

0.5

0.4

0.4

0.3

0.3

0.2

0.2

0.1

0.1

0
200

150

100

observables
mean (monte carlo)
mean (analytical)

0.9

50

50

100

0
400

300

200

100

100

200

300

Figure 4.12: (random walk.m) Probability density distribution of the observables for
10 (left) and respectively 100 (right) MonteCarlo simulations.
Error for n MonteCarlo simulations
P0=0, p=0.5, u=d=10, t=10

2
1.8
1.6
1.4

error

1.2
1
0.8
0.6
0.4
0.2
0
0

3
n

5
4

x 10

Figure 4.13: (random walk.m) Deviation between analytical and numerical expectation
over number of MonteCarlo simulation runs.
The probability of the random walk going up or down is incooperated in the program
by help of the if-condition. Since r=rand(1) is a random number, in particular
a uniformly distributed deviate in the interval [0, 1] , it can be compared with the
probability p . Take for example P(i = u) = 0.6 , i.e. the increment in the random
walk is positive with 60%, then the command if r<=p checks whether or not r lies in
the elected 60% of the unit interval, here [0, 0.6] . Alternatively, one might choose an
other 60%-fracture for the comparison, e.g. [0.2, 0.8] or [0, 0.2] [0.6, 1] .
Mathematical comments:
In MonteCarlo simulations, several representants of a random process are computed
and then averaged. The quality of the numerical expectation depends on the number
of observables: the bigger the sample, the better in general the approximation as
visualized in Figs 4.12, 4.13. The probability density distribution approximates a

4. Possible Implementations and Further Comments

67

normal distribution and numerical and analytical mean coincide. Anyhow, due to
the involved stochastics, there is no deterministic relation between the error and the
number of simulations, as Fig 4.13 clearly shows. Even for lots of repetitions, a
relatively big error might arise, take for example n = 3104 , error |anal num | 0.5 .
? integration.m
Writing longer and complex programs, a well-structured m-file management becomes
necessary. Instead of one huge file, the program is split into smaller self-sustaining
blocks / algorithms being realized in corresponding function files that are called by a
superordinate organizing script (function) file. This hierarchy of files enables an easy
and separate handling and debugging. Moreover, different subordinate files can be
flexibly linked together such that a variety of comparison and visualization routines
dependent on task and interests can come up. However, one can certainly also exaggerate the generation of subordinate files such that a supposed clear-ordered structure
gives way to a real mess. Every programmer has his/her personal preferences and
style in structuring and commenting files. Find your own way, but be aware that you
or maybe your friends want to work with your program in future. This presupposes
annotation.

function [integral,error] = quadrature(f,interval,no_nodes,flag)


% [integral,error] = quadrature(f,interval,no_nodes,flag)
% approximates the integral of the function f over the interval
% [interval(1) interval(2)]
% by help of Newton-Cotes formula using no_nodes number of nodes.
% flag determines the chosen quadrature rule:
% flag = Trapezoid => Trapezoid rule,
% flag = Simpson => Simpson rule
% error contains the order of the approximation error.
%
% f is a string containing the function expression in dependence
% on x, e.g. f=x^2, f=exp(x)+x
% =================================================================
if no_nodes < 2 no_nodes = 2; end

% check number of nodes

switch flag
case Trapezoid
x = linspace(interval(1),interval(2),no_nodes); % grid points
h = x(2)-x(1);
% mesh size
values=eval(f);
% function values
% computation of subintegrals
subintegrals = h/2*(values(1:no_nodes-1)+values(2:no_nodes));
% computation of integral

4. Possible Implementations and Further Comments

68

integral = sum(subintegrals);
error = h^3;
% approximation error
case Simpson
if mod(no_nodes,2)~=1
% check number of nodes
no_nodes = no_nodes+1;
disp(Number of nodes is increased by 1 to apply Simpson rule.)
end
x = linspace(interval(1),interval(2),no_nodes);
h = x(2)-x(1);
values=eval(f);
subintegrals = h/3*(values(1:2:no_nodes-2)+4*values(2:2:no_nodes-1)...
+values(3:2:no_nodes));
integral = sum(subintegrals);
error = h^5;
otherwise
error([Unknown flagflag.]);
end

=========================================
function [mean_int,integral] = monte_carlo(f,interval,...
trials,simulation)
% [mean_int,integral] = monte_carlo(f,interval,trials,simulation)
% computes the integral of a function given as string f dependent
% on x over the interval [xstart,xfinal] stochastically
% by means of Monte-Carlo simulations.
% "Area computation" - trial gives the number of shooting points
% ===============================================================
% computation of total area containing the function graph
xl = diff(interval);
x = linspace(interval(1),interval(2),xl*100);
y = eval(f);
extrema = [min([y,0]), max([y,0])];
yl = diff(extrema);
total_area = xl*yl;
if total_area ~= 0
hit_pos = zeros(1,simulation); % positive area being hit
hit_neg = zeros(1,simulation); % negative area being hit
% Monte-Carlo simulation
for j = 1:simulation
for i = 1:trials
% shooting procedure
r = rand(1,2);
% generation of random point
x = xl*r(1)+interval(1);
y = yl*r(2)+extrema(1);

4. Possible Implementations and Further Comments

69

value = eval(f);
% check whether point lays in the positive / negative
% integral area or not
if y>0 & y<=value
hit_pos(j) = hit_pos(j)+1;
elseif y<0 & y>=value
hit_neg(j) = hit_neg(j)+1;
end
end
end
% computation of integral from relation of shots and area
integral = (hit_pos-hit_neg)/trials*total_area;
mean_int = mean(integral);
else
% f is zero function or only one point
integral = 0;
mean_int = 0;
end

=========================================
% script file integration.m
% defines the considered function f to be integrated as string
%
dependent of x and the interval I as vector of start and final
%
point,
% initializes the number of grid points no_gp for the quadrature
%
rule and m and n for the Monte-Carlo simulation,
% calls the functions quadrature.m and monte_carlo.m:
%
[integral,error] = quadrature(f,I,no_gp,flag)
%
where flag = Trapezoid or flag = Simpson
%
[mean_int,observables] = monte_carlo(f,I,m,n)
% visualizes the distribution function for the observables as well
%
as the numerical means and the analytical mean,
% visualizes the approximate integral values and errors over
%
no_gp (~ step size h) and respectively over n
% ==================================================================
clear
f = exp(x)-2;
I = [0, 2];
int_ana = diff(exp(I)-2*I);
pic = 2;
if pic == 1
% plot probability distribution function
no_gp = 11;
m = 1000;

4. Possible Implementations and Further Comments

70

n = 10;
int_trap = quadrature(f,I,no_gp,Trapezoid);
int_simp = quadrature(f,I,no_gp,Simpson);
[int_mc, obs] = monte_carlo(f,I,m,n);
pdf_x = sort(obs);
pdf_y = linspace(0,1,n);
t = [0,1]; x = linspace(I(1),I(2),1e5);
figure
subplot(2,1,1);
plot(x,eval(f),k-,LineWidth,2)
hold on; plot(I,zeros(1,2),k-); hold off
title(f);
subplot(2,1,2);
plot(pdf_x,pdf_y,k*,[int_mc,int_mc],t,b--,...
[int_trap,int_trap],t,b-.,[int_simp,int_simp],t,b:);
hold on;
plot([int_ana,int_ana],t,r-,LineWidth,2);
title([Numerical integration for no\_gp=,num2str(no_gp),...
, m=,num2str(m),, n=,num2str(n)]);
legend(Observables,Monte-Carlo,Trapezoid,Simpson,...
exact,0)
hold off
else
% plot errors
no_gp = 3:4:100;
m = 100;
n = no_gp;
for i=1:length(no_gp)
int_trap(i) = quadrature(f,I,no_gp(i),Trapezoid);
int_simp(i) = quadrature(f,I,no_gp(i),Simpson);
int_mc(i) = monte_carlo(f,I,m,n(i));
end
e_trap = abs(int_trap-int_ana);
e_simp = abs(int_simp-int_ana);
e_mc = abs(int_mc-int_ana);
figure
subplot(2,1,1)
plot(n,int_mc,b--,no_gp,int_trap,m-.,no_gp,int_simp,r-)
title([Integral values over no\_gp resp. n, (m=,num2str(m),)]);
subplot(2,1,2);
plot(n,e_mc,b--,no_gp,e_trap,m-.,no_gp,e_simp,r-)
title([Corresponding errors]);

71

4. Possible Implementations and Further Comments

legend(Monte-Carlo,Trapezoid,Simpson,0)
end

exp(x)2
6
4
2
0
2
0

0.5

1.5

Numerical integration for no_gp=11, m=1000, n=10


1
0.8
0.6

Observables
MonteCarlo
Trapezoid
Simpson
exact

0.4
0.2
0
2

2.1

2.2

2.3

2.4

2.5

2.6

2.7

2.8

Figure 4.14: (integration.m) Top: Considered function. Bottom: Corresponding


integral values.

Integral values over no_gp resp. n, (m=100)


3
2.8
2.6
2.4
2.2
0

20

40

60

80

100

Corresponding errors
0.6
MonteCarlo
Trapezoid
Simpson

0.4

0.2

0
0

20

40

60

80

100

Figure 4.15: (integration.m) Integral values and errors in dependence of number


of grid points in the quadrature rules and respectively the number of MonteCarlo
simulations.

4. Possible Implementations and Further Comments

72

In the script file integration.m, the function under consideration is initialized as


string f such that the subordinate files quadrature.m and monte carlo.m evaluate f
with the command eval(). Instead, its definition in a separate function file f.m is
certainly also imaginable, then the command feval() is used for the evaluation.
Mathematical comments:
In contrast to numerical differentiation, numerical integration is a very difficult problem since it is ill-posed. But its need is realized in a lot of simulations, e.g. for the
assembly of the stiffness matrix in finite element methods. Quadrature rules do a good
job, e.g. NewtonCotes formulae, but in particular the quality of Gaussian quadrature
rules should be pointed out here. The Trapezoid rule has an error of order O(h3 ) ,
the Simpson rule of order O(h5 ) where h (# grid points) 1 which is illustrated in
Fig 4.15. MonteCarlo simulations could also be used for the integration but they are
undoubtedly not a reliable alternative. The errors are comparatively high and obey
no deterministic relation concerning the number of simulations, see Figs 4.14, 4.15.
? fitting.m

function a = fitting(x,y,p)
% a = fitting(x,y,p)
% finds the coefficients of the polynomial fit of degree p
% for the given data x,y in least-squares sense and
% returns them in the order from x^0 to x^p
% if p < 1,
% then by default: exponential fitting y = a(1)*exp(a(2)*x)
% ========================================================
% check of input data
n = length(x);
if n ~= length(y)
error(Input data must be of equal length.)
end
% convert x,y in row vectors
[m1,m2] = size(x); if m1 ~= 1 x = x; end
[m1,m2] = size(y); if m1 ~= 1 y = y; end
% check desired fit
if p < 1
% transform exponential fit
flag = exponential;
%
into linear one
p = 1;
if any(sign(y)~=1)
error([No exponential fitting possible,...
due to negative input data.]);
end
y = log(y);

4. Possible Implementations and Further Comments

73

else
flag = polynomial;
end
% initialization of linear system for polynomial fit
Xm = zeros(p+1,p+1);
Ym = zeros(p+1,1);
% assembly of right-hand side
YmM = zeros(p+1,n);
for i =1:p+1
YmM(i,:)=x.^(i-1);
end
Ym = YmM*y;
% assembly of system matrix
Xm(1,:) = sum(YmM);
for i=2:p+1
Xm(i,1:p) = Xm(i-1,2:(p+1));
Xm(i,p+1) = sum(x.^(p+i-1));
end
% computation of unknowns
a = (Xm\Ym);
% back transformation for exponential fit
switch flag
case exponential
a(1) = exp(a(1));
end

=========================================
% script file fit_plot.m
% plots the fitted curves (linear, quadratic, cubic, exponential)
% versus the given data x,y and
% determines the absolute errors in l_1 and l_2 and max-norm
% -> calls function fitting.m
% ==============================================================
clear
% input data
x = 0:1:10;
y = [1 0.01 5 3.9 5 4.7 8 9.1 9.4 11.5 21];
n = length(x);
no_fit = 4;
X = repmat(x,1,no_fit);

74

4. Possible Implementations and Further Comments

Absolute error over l norm

Data fitting

30

25

35
data
linear
quadratic
cubic
exponential

30

20

25

15

20

10

15

10

5
0

10

0
0

0.5
1
1.5
p (p=0: maxnorm)

Figure 4.16: (fit plot.m, fitting.m) Given data and corresponding fits.
Y = repmat(y,1,no_fit);
% determination of fitted values
for d = 1:no_fit-1
a = fitting(x,y,d);
fit(d,1:n) = polyval(fliplr(a),x);
end
a = fitting(x,y,0);
fit(no_fit,1:n) = a(1)*exp(a(2)*x);
fit = fit;
% determination of absolute error
e = abs(fit-Y);
enorm(1,1:no_fit) = sum(e);
enorm(2,1:no_fit) = sqrt(sum(e.^2));
enorm(3,1:no_fit) = max(e);
norm = repmat([1;2;0],1,no_fit);

% l_1-norm
% l_2-norm
% max-norm

% plot
subplot(1,2,1)
% curve fitting
plot(x,y,k*,X,fit);
title(Data fitting)
legend(data,linear,quadratic,cubic,exponential,0)
subplot(1,2,2);
% errors
plot(norm,enorm,.,MarkerSize,24);

4. Possible Implementations and Further Comments

75

title(Absolute error over l_p-norm);


xlabel(p (p=0: max-norm))

Mathematical comments:
Considering the absolute errors for the given test data, the cubic curve is the best fit
independent of the chosen lp -norm (cf. Fig 4.16).
In general, data fitting is of special interest for engineering or scientific applications
to give a feeling and deeper understanding for the relation between different parameters resp. the influence or dependence of one parameter on the other. Based on the
limited number of available experimental data (in discrete form), curve fits provide a
continuous mathematical model, i.e. a mathematical description of real-life.

76

5. Test Questions and Answers

Test Questions and Answers

Test 1
Task 1: (Matrix Manipulation)
1. Which calculation operations are defined for matrices in MATLAB?
2. What is the difference between A/B and A \ B?
3. Create a matrix A = (aij ) with 4 3 zero entries.
4. Set the element a1,3 = 4 .
5. Create a vector b of length 3 with random entries.
6. Place the vector b in the 3rd row of A
Solution:
1. +, -, *, /, \ ,

, (transpose)

2. Right division A/B means A B1 and left division A \ B means A1 B .


3. A = zeros(4,3)
4. A(1,3) = 4
5. b1 = rand(1,3), alternatively b2 = rand(3,1)
6. A(3,:)

= b1 or A(3,:)

= b2


Task 2: (If)
Write a function even.m that determines if the given input number n is even.
Input: scalar n
Output: scalar flag: flag = 1 if n is even, otherwise flag = 0
Solution:
function flag = even(n)
if mod(n,2)==0
flag = 1;
else
flag = 0;
end

Task 3: (For, Plotting)
x0 (t) = x(t),

x(0) = x0

Solve the given initial value problem in the time interval t [0, 20] for variable initial
value x0 (scalar), parameter (scalar) and step size h (scalar) by means of the
explicit Euler method. Plot the trajectory as red solid line.
Solution:
function euler(x0,lambda,h)

5. Test Questions and Answers

77

t = [0:h:20];
n = length(t);
x(1) = x0;
for i = 2:n
x(i) = (1+h*lambda)*x(i-1);
end
plot(t,x,r-);

Test 2
Task 1: (Matrix Manipulation)
1. Create a row vector a whose elements are ascending integer numbers from 11 to
253.
2. Create a vector b of same size as a with random numbers.
3. Define c as componentwise product of a and b.
4. Create the matrix A with c on the diagonal.
5. Determine the rank of A.
6. Determine the determinant of A.
7. Create the vector d with the same elements as b but in opposite order.


A dT
8. Create the matrix B =
.
b 106
Solution:
1. a = [11:253]
2. b = rand(size(a))

or b = rand(1,length(a))

3. c = a.*b
4. A = diag(c)
5. rank(A)
6. det(A)
7. d = b(length(b):-1:1)

or d = fliplr(b)

8. B = [ A , d ; b , 1e6 ]

Task 2: (For, Plotting)
x0 (t) = x(t),

x(0) = x0

Solve the given initial value problem in the time interval t [0, 100] for variable scalar
input values x0 , and step size h by means of the explicit as well as implicit Euler
method.
Plot the trajectory of the explicit Euler as blue dashed line, the one of implicit Euler
as green dash-dotted line and the initial point as red star.

5. Test Questions and Answers

78

Give the figure the title Numerical approximations. Label the axes as t and x -axis.
Define the legend.
Solution:
function euler(x0,lambda,h)
t = [0:h:100];
n = length(t);
xE(1) = x0;
xI(1) = x0;
for i = 2:n
xE(i) = (1+h*lambda)*xE(i-1);
xI(i) = (1-h*lambda) \ xI(i-1);
end
plot(t,xE,b--,t,xI,g-.,t(1),x0,r*);
hold on
title(Numerical approximations);
xlabel(t);
ylabel(x);
legend(explicit Euler,implicit Euler,initial point);
hold off

Task 3: (Algorithmic Programming)
Write a function mysort.m that sorts the elements of a given vector v in descending
order.
Input: vector v
Output: vector vsort (sorted)
You are allowed to use MATLAB build-in functions.
Solution:
Ansatz 1: using MATLAB build-in function sort():
function vsort = mysort(v)
tmp = sort(v);
vsort = tmp(length(temp):-1:1);
Ansatz 2: using MATLAB build-in functins sort(), fliplr(), flipud():
function vsort = mysort(v)
tmp = sort(v);
[m,n]= size(tmp);
if m == 1
vsort = fliplr(tmp);
else
vsort = flipud(tmp);
end
Ansatz 3: using MATLAB build-in function max():
function vsort = mysort(v)
n = length(v);
for i = 1:n

5. Test Questions and Answers

79

[value,pos] = max(v);
vsort(i) = v(pos);
v = v([1:pos-1, pos+1:n-i+1]);
end
Ansatz 4: using a binary search (without MATLAB features):
function vsort = mysort(v)
n = length(v);
vsort = v(1);
for i = n:-1:2
v = v(2:i);
vc = v(1);
w = vsort;
m = length(w);
pos = 1;
flag = 0;
while (flag == 0) & (m > 0)
mid = round(m/2);
if vc > w(mid)
w = w(1:mid-1);
elseif vc < w(mid)
pos = pos + mid;
w = w(mid+1:m);
else
pos = pos + mid;
flag = 1;
end
m = length(m);
end
vsort = [vsort(1:pos-1) vc vsort(pos:n-i+1)];
end

Test 3
Task 1: (Matrix Manipulation, Sparse Matrix)
1. Define n equal 100 . Create a sparse matrix S of size n n with maximal 4n
non-zero entries.
2. Set the first row of S equal to 1 and the last element sn,n equal to 1.5 104 .
3. Create a vector a of length n whose entries are alternatively 2 and 4 .
4. Create a vector b of length n whose entries are ascending integers starting at 1
with increment 2 . Create a vector c of same length as b whose entries are the
same as the ones of b but in opposite order.
5. Create a sparse diagonal matrix T with a on the main diagonal, b on the third
lower subdiagonal and c on the second upper subdiagonal.

80

5. Test Questions and Answers


6. Which elements
a
2 none
b
2 none
c
2 none

of a, b, c are missing in the diagonals of T?


2 first ... (number) 2 last ... (number)
2 first ... (number) 2 last ... (number)
2 first ... (number) 2 last ... (number)

7. Create U as sum of S and T.


8. Define the vectors x and y whose n entries are equidistantly distributed between
0 (first value) and 1 (last value).
9. Create corresponding meshgrid matrices X and Y based on the vectors x and y.
10. Plot U over the mesh given by X and Y as surface contour plot.
Solution:
1. n = 1000; S = spalloc(n,n,4*n);
2. S(1,:) = ones(1,n); S(n,n) = 1.5e4;
3. if n is even: t = [2,4]; a = repmat(t,1,n/2); or
a(1:2:n-1) = 2*ones(1,n/2); a(2:2:n) = 4*ones(1,n/2);
in general: t = [2,4]; a = repmat(t,1,round(n/2)); a = a(1:n); or
a = 2*ones(1,n); a(2:2:n) = 4*ones(1,floor(n/2));
resp.
a(2:2:n) = 4*ones(1,round((n-1)/2);
4. b = [1:2:2*n]; c = fliplr(b);
5. T = spdiags([a,b,c],[0,-3,2],n,n);
6. a none; b first 3; c last 2;
7. U = S+T; U: sparse;
U = full(S+T); U: full;

U = full(S)+T; U: full;

8. x = linspace(0,1,n); y = x;
9. [X,Y]=meshgrid(x,y);
10. surfc(X,Y,U)

Task 2: (Matrix Assembly, Plotting)
Solve the Dirichlet boundary value problem
u00 (x) = 1,
x (1, 1)
u(1) = u(1) = 5
on a regular grid using the finite difference method with standard second differences.
Plot u over x as magenta dash-dotted line of width 2. Label the axes and give the
figure a title.
Implementation:
Input: number of grid points
Output: u on all grid points (including boundary points)
grid points
mesh size (step size)

81

5. Test Questions and Answers


Solution:
function [u,x,h] = dirichlet(n)
% [u,x,h]=dirichlet(n)
% solves the Dirichlet BVP u(x)=1, u(-1)=u(1)=5 on a regular grid
% (mesh size h) for given number of grid points n and
% plots u over the grid points x
% ==================================================================
x = linspace(-1,1,n);
% grid points
h = x(2)-x(1);
% mesh size
% assembly of difference matrix L for interior grid points
e = ones(n-2,1);
d = -2*ones(n-2,1);
L = spalloc([e,d,e],[-1,0,1],(n-2),(n-2))/h 2;
% assembly of right-hand side f for interior grid points
f = e;
f(1) = 1-5/h 2; f(n-2) = f(1); % incooperation of boundary points
% computation of unknowns
u = L \ f;
u = [5,u,5];
% inclusion of boundary values
% visualization
plot(x,u,m-.,LineWidth,2);
title([Numerical approximation of Dirichlet BVP for ,num2str(n),...
grid points]);
xlabel(x); ylabel(u);


Task 3: (Algorithmic Programming)
Write a function neighbor.m that determines for a point (xp , yp ) the nearest neighbor
with respect to the Euclidean norm out of the set S = {(xi , yi ) | i = 1, ..., m} and
additionally plots all points of S as black stars, the point (xP , yP ) as blue circle of
size 10 and its nearest neighbor (xN , yN ) as red cross of size 10.
Implementation:
Input: point as column vector
P = (xP , yP )T

x1 x2 ... xm
set matrix S =
y1 y2 ... ym
Output: nearest neighbor point as column vector N = (xN , yN )T
distance between P and N
position of N in S (in which column of S is N stated?)
Solution:
[N,d,pos] = neighbor(P,S)
% determination of nearest neighbor
D = sqrt((S(1,:)-P(1)). 2 + (S(2,:)-P(2)). 2);
[d,pos] = min(D);
N = S(:,pos);
% visualization
plot(S(1,:),S(2,:),k*);

% Euclidean distance

5. Test Questions and Answers

82

hold on
plot(P(1),P(2),bo,MarkerSize,10);
plot(N(1),N(2),r+,MarkerSize,10);
hold off


Potrebbero piacerti anche