scientific computing with matlab - pudn.comread.pudn.com/downloads143/ebook/624396/scientific...

83
Kathmandu University School of Science Department of Mathematics Lecture Notes SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke T ECHNISCHE UNIVERSITÄT KAISERSLAUTERN Fachbereich Mathematik Arbeitsgruppe Technomathematik Winter Semester 2005

Upload: phungcong

Post on 07-Sep-2018

259 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

Kathmandu University

School of Science

Department of Mathematics

Lecture Notes

SCIENTIFIC COMPUTING WITH

MATLAB

Dr. Nicole Marheineke

TECHNISCHE UNIVERSITÄT

KAISERSLAUTERN

Fachbereich MathematikArbeitsgruppe Technomathematik

Winter Semester 2005

Page 2: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

Course Overview 1

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 par-ticularly split into two parts, a theoretical and a practical one. In the theoretical part,mathematical methods and algorithms concerning numerical analysis are presentedthat are then implemented by the students in the practical part. For the implementa-tion, 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 algo-rithms

• to learn programming

• to apply MATLAB for solving mathematical problems numerically and visualiz-ing 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

• Monte–Carlo simulations

Literature:

[1]

[2][3]

[4]

[5]

K. Sigmon: MATLAB Primer, 3rd ed, University of Florida, Department of Math-ematics, 1993 (print-out provided)MATLAB Quick Reference (print-out provided)MATLAB Help Desk (on-line help, installed in MATLAB)Further documentations, practical introductions, guides and tutorials for MAT-LAB can be downloaded for free from the internet:

> go on the webpage http://www.yahoo.com or http://www.google.com> search for MATLAB

N.Marheineke: Lecture notes – Numerics for differential equations, KathmanduUniversity, Department of Mathematics, 2005J. Stoer and R.Bulirsch: Introduction to numerical analysis, Springer, 2002

Page 3: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

CONTENTS 2

Contents

1 What is Scientific Computing? 4

2 Introduction into MATLAB 5

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

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

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

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

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

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

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 Runge–Kutta 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

? Monte–Carlo Simulation . . . . . . . . . . . . . . . . . . . . . . . . . 25

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

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

Page 4: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

Contents 3

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

Page 5: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

1. What is Scientific Computing? 4

1 What is Scientific Computing?

Real-life problems in science, engineering and technology can be in general describedby a mathematical model. This might be for example a set of differential equations, anoptimization or control problem and/or a statistical data analysis. Mostly, the arisingmathematical models are highly complicated and too complex to be solved analytically.Hence, appropriate numerical methods must be applied to provide approximative so-lutions with help of the computer. The procedure of deriving numerical algorithms,implementing them in a programming language and interpreting their results is knownas Scientific Computing.

This course ”Scientific Computing with MATLAB” focuses on the treatment of ordi-nary and partial differential equations as well as statistical and stochastical problemsby using the software tool MATLAB.

Actually, scientific computing is not theoretically teachable but only practically learn-able, since programming mainly depends on the individual way of dealing with prob-lems, thinking and structuring facts in a logical order as well as on personal preferencesand experiences. Thus, two programs written by two independent persons for the samemathematical algorithm will always differ. There is no unique solution for a program-ming task. Instead, the quality of a program is measured in terms of computationtime and number of operations. These independent parameters are strongly affectedby the used soft- and hardware due to the required data storage. Therefore, a programrunning 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 pow-erful possibilities and build-in functions and undoubtedly far away from completeness,the exercise tasks with helpful hints and MATLAB commands in Ch 3 are designedto appeal for a constructive self-study in programming. In Ch 4 possible implementa-tions and further extensions for advanced programmers are presented. Moreover, thesimulation 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 andelement methods [4] as well as curve fitting, interpolation or integration routines [5] inaddition to the limited number of given examples. Apart from differential equations,statistics and stochastics, MATLAB can certainly be applied for handling optimizationand control problems as well as all other imaginable mathematical algorithms.

Have fun in discovering the scope and power ofMATLAB.

Page 6: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

2. Introduction into MATLAB 5

2 Introduction into MATLAB

2.1 What is MATLAB?

MATLAB (MATrix LABoratory) is an interactive, matrix-based system for scientificand engineering numerical computation and visualization. It is a powerful tool thatmight solve complex numerical problems in a fraction of time required by other pro-gramming languages such as FORTRAN or C.

PSfrag replacements

Programming&

VisualizationTool

• to develop ownsoftware

• to evaluate date

• to visualize data

• m-files

MathematicalLibrary

• build-infunctions

• tool boxes(can be boughtand added)

Calculator

• calculationoperations

• controlstructures

interactive

OtherSoftware

read in/read outfiles

easily linked

• commercial tools

• C-program

• data files

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)

Page 7: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

2. Introduction into MATLAB 6

• 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 · 10−10 ∧

= 2.79e-10, blank spaces must beavoided.

Operations: + addition- subtraction* multiplication∧ power\ left division =⇒ Note that for scalars the left and the right/ right division division yield the same result!

Build-in functions: abs() absolute value, sqrt() square rootreal() real part, imag() imaginary partround() rounded integer value, sign() signum functionexp() exponential function, log() logarithmsin() sine, cos() cosinetan() tangent, gamma() gamma function

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

>> ans = 4

2.4 Entering Vectors and Matrices

MATLAB works with only one object, namely a rectangular numerical matrix withpossibly complex numbers or characters (text strings) as entries. Hence, scalars arerepresented 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

Page 8: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

2. Introduction into MATLAB 7

• 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 >> a = [1 4.6 27+5i 6e5]

Column vector: b =

14.6

27+5i6 ·105

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

>> b = [ 1 ENTER

4.6 ENTER

27+5i ENTER

6e5 ]

Matrix: A =

(

1 2 34 5 6

)

>> A = [1,2,3;4,5,6] or alternatively >> A = [1 2 3;4 5 6] or>> A = [ 1, 2, 3 ENTER

4, 5, 6 ]or

>> A = [ 1 2 3 ENTER

4 5 6 ]

The elements of matrices are stated in square brackets [.]. Thereby, the componentsin a row are separated by comma or blank, the ones in a column by semicolon or newline.

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 miss-ing, 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 andevaluated. MATLAB statements are usually of the form

variable = expression or simply expression

Expressions are usually composed from operators, functions and variable names. Eval-uating an expression produces a matrix that is displayed on the screen and assignedto the variable for future use. Hence, all variables represent matrices. The name of avariable has at least 1 character and at most 19. It might contain digits, but no opera-tion signs and the first character is always a letter, a, A, b, B, c, C etc. MATLABdistinguishes 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.’

Page 9: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

2. Introduction into MATLAB 8

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 cur-rently in the workspace – except from the permanent ones. A variable can be deletedfrom 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 ofthe statement is a semicolon. The use of the semicolon is essential in avoiding theunwanted printing of intermediate results, cf.input >> a = 2+2; ENTER =⇒ no output

A statement is normally terminated in a single line with ENTER . However, a statementcan be continued to the next line with three or more dots, ..., followed by ENTER ,>> a+b+c+... ENTER

+d+e;

On the other hand, several statement can be placed on a single line if separated withcommas or semicolons,input: >> x = 1, y = 2; z = 3 ENTER =⇒ output: >> 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 commandsave before exiting causes all variables to be written to a non-human-readable diskfilenamed matlab.mat. When restarting MATLAB, the command load restores theworkspace 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: +, -, *, ∧ , \ , /. Andadditionally, ’ represents the conjugate, transpose. The matrix-matrix operationsresp. matrix-vector operations obey the rules of linear algebra. If the sizes of theobjects are incompatible for the operation, an error message is produced on the screen.Note that in case of matrix-scalar operations (for addition, subtraction, multiplicationand division) the scalar operates componentwise on the entries of the matrix.

The matrix division deserves some special comments. If A is an invertible squarematrix and b a compatible column resp. row vector, then

Page 10: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

2. Introduction into MATLAB 9

>> x = A \ b gives the solution of the linear system Ax = b , i.e. x = A−1b>> x = b / A gives the solution of the linear system xA = b , i.e. x = bA−1 .In left division, if A is square, then it is factored using Gaussian eliminations. If A isnot square, it is factored using Householder orthogonalization with column pivoting.The factors are used to solve the under- or overdetermined system in the least squaressense. 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 otheroperations are matrix operations. It is important to mention that these other opera-tions *, ∧ , \ , / 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 ap-plied on matrices, they are evaluated componentwise.

• a few build-in functions in MATLAB deal with the whole matrix and not onlywith its components, e.g. expm(), sqrtm(), logm().

Vector functions: length()length, norm() normmax() maximum, min() minimumsum() sum of components, prod() product of componentssort() sorting, median() medianmean() mean, std() standard deviationany() any non-zero values? all() all non-zero values?

Matrix functions: size() size, rank() rankinv() inverse, det() determinantnorm() norm, cond() conditioneig() eigenvalues, chol() Cholesky-decompositionlu() LU-decomposition, qr() QR-decompositionschur() Schur complement, hess() Hessenberg form

Matrix building functions:

zeros() matrix of zerosones() matrix of oneseye() identity matrixrand() randomly generated matrixdiag() create or extract diagonalstoeplitz() see help toeplitz

For example, zeros(m,n) produces a (m × n) -matrix of zeros and zeros(n) one ofsize (n × n) . The command zeros(size(A)) generates a matrix of zeros having thesame size than the matrix A. Analogously for ones(), eye(), rand(). Moreover,matrices can be build from blocks:

Page 11: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

2. Introduction into MATLAB 10

>> 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 argumentsfor row and column or alternatively by a single argument (the respective other one isby default 1) as exemplified above. The last has the advantage that row and columnvectors can be treated similarly. The command length() provides the length of avector, 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 andif. For and while-loops slow MATLAB down, try to avoid them and use insteadmatrix-vector operations.

For:

The general form of a for-loop isfor counter = start value:increment:end value

statements

end

The statements are executed for all values of the counter variable, seev = 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 iswhile 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;

Page 12: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

2. Introduction into MATLAB 11

a = a-0.1;

end

If:

The general form of a simple if-statement isif relation

statements

end

The statements are executed only if the relation is true. Multiple branching is alsopossible, 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 matrixif i==j

A(i,i) = 1

elseif i>=j

A(i,j) = -1

else

A(i,j) = 0

end

Relational operators: < less than> 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 usedin a relation. Relations may be connected or quantified by logical operators.

Logical operators: & and| or∼ notxor exclusive or

Further useful operators are any and all.

Applying the listed operators above on scalars, the result is 1 or 0 depending onwhether the relation is true or false. When applied to matrices of the same size, arelation 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 ofthe relation matrix are non-zero. Hence, if A==B statements end is only executed

Page 13: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

2. Introduction into MATLAB 12

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 calledm-files because they must be saved with ”.m” as the last part of their filename. M-filesare usually created by using the local text editor. There are two types of m-files: scriptand function files.

Script file:

• contains a sequence of standard MATLAB commands that could alternativelybe given interactively in a MATLAB session

• is executed by calling its name in the command line, i.e. if the file is saved astest.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 namein 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 errorscan be easily corrected.Useful build-in functions: input, keyboard, pause, disp

Function file:

• provides the extensibility to MATLAB, since it prescribes a function that hasbeen 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 mustread

function myf

The function has m input and n output parameters if the first line declares – addi-tionally to the function name – also the input and output parameters in the followingform

function [out1,out2,...,outn] = myf(in1,...,inm)

This line is essential for the execution of the function. Without these declarations thefile 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 byinput: >> [a,b] = operation(3,5) =⇒ output: >> a = 8 >> b = 15

Page 14: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

2. Introduction into MATLAB 13

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

=⇒ output:>> C = 2 1

1 2

>> D = 1 1

1 1

A function can be called without the full set of input and output parameters by helpof the commands nargin and nargout.nargin: number of input arguments by callnargout: 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. Commentsare 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 ofcomments stated in the m-file. Such a block is finished by an empty row or a MATLABexpression.

2.9 Graphics

MATLAB can produce 2D and 3D plots of curves, 3D mesh surface plots as well as3D 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, thecommand plot(x,y) opens a graphics window and draws an x-y plot of the elementsof 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 graph-ics. If a current graphics window (figure) should be kept, another one can be openedwith the command figure(2) or simply figure which then becomes the current figurewhere 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 onewhere 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

Page 15: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

2. Introduction into MATLAB 14

Colors: y yellow, 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 usingthe 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 smallplots can be placed in one figure, see help subplot.

Other specialized 2D plotting functions that are worth to be explored via help arepolar, 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 thischapter is only meant to give a brief survey of the possibilities and the build-infunctions in MATLAB, and it is certainly far away from completeness. Hence, do nothesitate to consult the MATLAB User’s Guide, Reference Guide or the on-line helpto get more detailed and updated informations.

Page 16: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 15

3 Exercises

The following exercise tasks taken from the fields of differential equations, statisticsand stochastics are designed for a constructive self-study in programming. Every taskrequires some new MATLAB features that are provided in the list of helpful build-in functions. Once introduced, the features should be continuously applied in theongoing tasks such that they become familiar to the user. Since programming livesfrom practice, it is recommended to supplement the given tasks by further examplesof 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 num-bers

• 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 ·10−3) as row and as column vector.

• Enter the matrix

(

1 5 74+ 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 MATLAB’s answer?

• Enter the command clear and afterwards who.What is MATLAB’s 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

• Define A =

1 2 34 5 67 8 9

, B = 3A + I and b =

171921

in MATLAB

where I ∈ R3×3 denotes the identity matrix.

Page 17: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 16

• Compute AT , AB , A− B , A2 (i.e. AA ), A−1 B , AB−1 .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 theinput?

• 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 meansof 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 vectorof various length. Do not forget the description of the function in the first commentline, 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)

y2 =

1061220

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

Page 18: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 17

Compare your results with the ones being obtained from the MATLAB build-in func-tions 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 itsstandard deviation stdev.

3. Visualize the input vector, its mean and standard deviation graphically. There-for, 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 plotsthe 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

x′(t) = y − xg = f1(x, y), y′(t) = −x − yg = f2(x, y), g ∈ R (3.1)

Write a function stability.m in MATLABfunction stability(g,x0,y0,tau)

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

Page 19: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 18

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

A =

(

−g 1−1 −g

)

.

The eigenvalues λ1 , λ2 of A determine the stability behavior of the system:

• maxi Re(λi) < 0 ⇒ system is asymptotically stable

• maxi Re(λi) = 0 ⇒ system is stable, since index i(λi) = 1

• maxi Re(λi) > 0 ⇒ system is instable

Write a function stability1.m in MATLABfunction stability1(g)

that computes the eigenvalues for varying g and displays the stability behavior of thecorresponding 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 ifrelation 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 valuesx0 = x(t0), y0 = y(t0) and time step τ can be computed by means of the explicitEuler 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 initialvalues x0, y0 and time step tau. Let the starting time t0 for your computation betStart=0 and choose the final time tEnd appropriately. Store the computed valuesxn , yn as components in corresponding vectors x and y. Plot the vector x against y.

Page 20: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 19

The initial values should thereby be marked by a red circle and the trajectory plottedby 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 eval-uated the inner statements, the counter is updated by the arbitrary chosen incrementand the inner statements are evaluated with the new value of the counter. For-loopsare the appropriate tool for implementing recursions (cf. right example). Note that incertain cases (left example) for-loops should be replaced by vector-matrix operationsto 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-loopmight 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, andthe counter must be updated manually in the loop, cf. middle example. On the otherhand, while-loops are very appropriate for implementing recursions with additionalbreaking 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 away 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 alltrajectories 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 stablecase?

Page 21: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 20

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

Consider the following initial value problem

y′′′(x) + y′′(x) + y′(x) + y(x) = 0, y(0) = 0, y′(0) = 1, y′′(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′ and y′′ for x ∈ [0, 2] by help of theexplicit Euler method.

3. Plot the numerical results for different step sizes h ∈ 1, 0.5, 0.25, 0.1, 0.01, 0.001in one figure (i.e. one figure for all approximations of y , one for y ′ and one fory′′ ) 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 thefollowing commands which take a string as argument:

title() figure titlexlabel() x-axis label (horizontal axis)ylabel() y-axis label (vertical axis)gtext() place text on the graph using the mousetext() 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 Runge–Kutta Method

A simple model for the predator-prey relationship (e.g. between snakes and mice) isgiven by the following system of differential equations

x′(t) = αx(t) + βx(t)y(t)

y′(t) = γy(t) + δx(t)y(t)

where x and y represent the number of creatures per species. Implement the classical(standard) explicit Runge–Kutta method with the parameters

α =1

4, β = −

1

100, γ = −1, δ =

1

100,

the initial valuesx0 = 80, y0 = 30

Page 22: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 21

and the step sizes h ∈ 1, 0.5, 0.1 . Compare the results with the respective approx-imations given by the explicit Euler method for the same step size. Plot therefor thecoordinates (xi, yi) . Choose for your computations the time interval t ∈ [0, 20] .

Recall: Scheme of classical explicit Runge–Kutta method [4]Consider the arbitrary system of ODEs x′(t) = f(t,x) with step size h , then thegeneral Runge–Kutta scheme (b, c,A) with s levels reads

xn+1 = xn + hs

i=1

bi ki

k1 = f(tn + h c1,xn)

ki = f(tn + h ci,xn + h

i−1∑

j=1

aij kj), i = 2, ..., s

In the classical RK-method s = 4 , the coefficients are given by the following Butcherarray

c1 a11 0 0c2 a21 a22 1/2 1/2 0c3 a31 a32 a33 1/2 0 1/2 0c4 a41 a42 a43 a44 1 0 0 1 0

b1 b2 b3 b4 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 thevector v and states whether or not x is contained in v:

function flag = search(x,v)

Input: scalar x, vector vOutput: 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 – especiallyby 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 ofthe vector. If x is smaller than this value, the search is restricted on the lower halfof the vector, otherwise on the upper one. In the next step, x is compared with theelement in the middle of the respective half. This division into two parts is continueduntil 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 writeyour own sorting function mysort.m

function sortv = mysort(v)

Page 23: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 22

3.4 ODE-Solvers and Efficiency of Algorithms

? ODE: Implicit One-Step Methods, Newton Method

Solve the Van-der-Pol equations

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

y′ = 10 (1 − x2)y − x, 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 im-plicit Center-point rule zn+1 = zn + τ f((zn +zn+1)/2) with step size τ = 10−3 .

2. Solve the arising non-linear system of equations F(zn+1) = 0 with the Newtonmethod and use hereby the values of the previous time step as initial values forthe iteration, i.e. z

(0)n+1 = zn . Stop the iteration, if the difference of the iteration

values satisfies ‖z(k+1)n+1 − z

(k)n+1‖ ≤ 10−8 .

3. Plot the resulting (x, y) -values, plot the number of required iteration steps overthe 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 forthe respective routines and test them on the Van-der-Pol equations.

5. Compare the number of function evaluations (flops) and the required time forthe total computation (tic, toc). Which method is the most appropriate onefor solving the Van-der-Pol equations?

6. Try to speed up the method by providing the inverse of the Jacobian matrixanalytically.

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 thestatement

• flops(0), statement, flops: returns the number of flops performed for theexecution 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 linearsystem. Use alternatively, x=inv(A)*b, compare the required time and flops. Whichmethod is more efficient for solving a linear system?

Page 24: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 23

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

h2(−ui−1,j − ui,j−1 + 4ui,j − ui+1,j − ui,j+1) with h =

1

25

and state the resulting linear system Lhuh = fh for a row-wise numbering. Computethe approximations for the following problems and visualize them graphically:

• f(x, y) = 1 in Ω and u(x, y) = 0 on ∂Ω ,

• f(x, y) = 0 in Ω and 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 -directionand k in y -direction.

2. Compute the approximations of the problems for different tuples (h, k) of stepsizes, h ∈ 1/10, 1/20, 1/25, 1/50, 1/100 , k ∈ 1/10, 1/20, 1/25, 1/50, 1/100and measure elapsed time and number of operations.

3. Use the approximation with respect to h = k = 1/100 as reference solutionand determine and plot the numerical errors. Are there any relations betweenmaximal 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−xi−1 and kj = yj−yj−1 , and derive a 2D-stencilfrom the 1D-discretization given in [4], Exercise Task 6.2

−u′′(x) ≈2

hi + hi+1

(

ui − ui+1

hi+1+

ui − ui−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 : lowersubdiagonals

• 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

Page 25: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 upwith 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 in-terval [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 in-terval [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 circlesb) 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 whoseedges are black-colored

Moreover, commands such as grid, xlabel, ylabel, zlabel, title can beapplied.

• [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 ofx and Y column-wise copies of y

• surf(X,Y,Z): generates a surface plot of the matrix Z on the 2D-grid given bythe 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 givenby the matrices X and Y and additionally a contour plot. Note that X , Yand Z must be of same size.

• contour(X,Y,Z,n): generates a contour plot with n level curves of the matrixZ on the 2D-grid given by the matrices X and Y . Note that X , Y and Zmust 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-zeroentries

• speye(n): generates a sparse identity matrix of size n × n

Page 26: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 25

• spdiags(v,0,n,n): generates a sparse quadratic matrix of size n × n with thevector 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

? Monte–Carlo Simulation

Implement a random walk and compare its analytical and numerical expectations.Therefor, consider a discrete stochastic process (Φt, t ∈ 0, 1, ..., T) with independentidentically distributed increments Ψt = Φt − Φt−1 ∈ u,−d , u , d ≥ 0 . Then, arandom walk reads

Φt = Φ0 +t

i=1

Ψi, t = 1, 2, ...T

where the probability of the increment Ψi being u is given by p and respectively ofbeing −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 ofMonte–Carlo simulations. Therefor, observables of Φt are generated in n indepen-dent simulation runs, whose values are then averaged, i.e. µΦt

=∑n

i=1(Φt)i/n . Forcomparing analytical and numerical expectation, plot the probability distribution func-tion for the observables of Φt and visualize the analytical mean as red solid line andthe numerical one as blue dashed line (line width 2). The plotting requires that thenumber of simulations n is treated as 100% and thus scaled as 1 and that the re-spective percentages are drawn over the sorted values of the observables (Φt)i as blackstars (marker size 6). For n → ∞ the obtained probability distribution function isa normal distribution where analytical and numerical mean coincide. Visualize thisrelation 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

Page 27: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 26

%

% 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 auto-matically the used number of input arguments in nargin. If nargin does not coincidewith the number of inputs stated in the declaration line of the function, default valuesmust be provided. Analogously, nargout for number of output arguments by call.

? Numerical Integration

Perform numerical integration by help of Newton–Cotes 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.

∫ x0+h

x0

f(x) =h

2(f(x0) + f(x0 + h) + O(h3) Trapezoid rule

∫ x0+2h

x0

f(x) =h

3(f(x0) + 4f(x0 + h) + f(x0 + 2h)) + O(h5) Simpson rule

The quality of the approximated integral depends on the integral length h . Thus, itis reasonable to introduce an equidistant grid xi = i h , i = 1, ..., N and divide I intosmaller subintervals Ii = [xi−1, xi] .Alternatively, a Monte–Carlo simulation can be used for the computation of the inte-gral. Since the integral represents the area between the x -axis and the graph of thefunction, one might embed the function into an rectangle as visualized below.

−0.25 0 0.25 0.5 0.75 1 1.25−0.25

0.25

0.75

1.25

1.75

2.25

2.75

3.25

3.75

Figure 3.1: Integral represents area of marked region.

Page 28: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 27

Generating m random points within this rectangle of size A , one counts the num-ber of points p laying in the area of interest. Then, the integral of the function isapproximated by

∫ xm

x0

f(x)dx ≈p

mA.

Repeating this procedure n -times yields an reasonable numerical expectation for theintegral.

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 functionExample: x = 0; feval(’exp’,x) =⇒ ans = 1, easier: exp(x)

• switch, case, otherwise: comparable to if, elseif, else but for text stringsSyntax: 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 ruleExample: x = 0:pi/8:2*pi; y = sin(x); integral = trapez(x,y);

Page 29: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

3. Exercises 28

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

? Curve Fitting Routines

Implement least-square curve fitting routines (linear, quadratic, cubic and exponen-tial). Let the observed data be given by n tuples (xi, yi) , i = 1, ..., n . In a polynomialfitting ansatz of degree p , the error reads

e2(a0, ..., ap) =

n∑

i=1

(yi −

p∑

k=0

akxki )

2

The coefficients ai are determined in such a way that the error is minimal with regardto least squares, i.e.

∂e2(a0, ...ap)

∂ak

= 0, for k = 0, ..., p

which leads to (p + 1) equations for (p + 1) unknowns.In case of p = 1 , the equations are then for example

∂e2(a0, a1)

∂a0= −2

n∑

i=1

(yi − (a0 + a1xi)) = 0

∂e2(a0, a1)

∂a1= −2

n∑

i=1

(yi − (a0 + a1xi))xi = 0

An exponential fitting ansatz can be rewritten in terms of the linear one, since

yi = c0 exp(c1xi) =⇒ ln(yi) = ln(c0) + c1xi.

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 andreturns 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 coefficientvector p

Page 30: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 29

4 Possible Implementations and

Further Comments

The presented implementations should be understood as sample programs for the exer-cises and not as unique solution. Alternative implementations for the same algorithmare always possible. Depending on the experiences with MATLAB, varying programsof complexity are given for the same task in the following. The basic ones apply onlythe already known MATLAB functions, whereas the extended ones introduce new andinteresting features that are worth discovering in detail. Apart from implementation,this chapter focuses also on the discussion of the simulation results in terms of scien-tific computing. Thereby, the evaluation of the numerical results always requires theunderstanding 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 iseasily doable by help of the introductory part in Ch 2. In particular, it should givean insight into the powerful tool of MATLAB as interactive calculator, raise curiosityand encourage to further independent studies and application.

MATLAB Warnings and Error Messages:MATLAB checks the syntax of the input commands and states warnings and errormessages on the screen in case of mistakes. Thereby, it helps the user by alreadygiving ideas what and where (in which line) the mistake could possibly be, e.g. missingbracket, missing comma or semicolon, capital starting letter for a function name, sizesof matrices are incompatible for certain operations. MATLAB’s suggestions are mostlyabsolutely correct such that it is worth studying and following them. If function andvariable names are spelled wrongly or do not exist in the workspace, MATLAB statesa list with alternatives whose spellings are similar and might be meant. Hence, ifone does not know or remember a name precisely, it makes sense to try out reasonablenames like for example bessel(5) in Task 1. In this way, one finds out that MATLABhas a bunch of bessel functions, i.e. besseli(), besselj(), besselk(), bessely()

that expect different input arguments. To get more information about the respectivefunctions and their syntax call help function of interest. Moreover, MATLABproduces warnings if the results of certain operations are not reliable, e.g. division byzero or inversion of a singular matrix (cf. Task 4, A−1B ). The respective operationsshould 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 isa function file that outputs mean and standard deviation for a variable input datavector.

Page 31: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 themedian of the input data vector is computed. For sorting the input vector and findingthe position of the median, the MATLAB functions sort() and if-condition areapplied in statistics ext.m. Moreover, the simple plotting routine producing Fig 4.1is replaced by the graphical visualization of the probability distribution function inFig 4.2. To emphasize the median as big red circle, the MarkerSize is increased upto12 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

% ==========================================================

Page 32: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 31

0 20 40 60 80 1000

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

0 200 400 600 800 10000

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

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).

0 0.2 0.4 0.6 0.8 10

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

0 0.2 0.4 0.6 0.8 10

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

Figure 4.2: (statistics ext.m) Probability distribution function for the samples ofFig 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

Page 33: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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. Thebigger the sample, the clearer the distribution function turns out to be a straight lineas 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 (com-putational speed) for matrix-vector operations. Hence, it is recommended to programas much as possible in terms of matrices and vectors, instead of scalars. The scalarresp. 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

Page 34: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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, theprogram must be called several times and the results plotted in the same figure by helpof 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 overcomesthis limitation in stability v.m. Here, the initial values are not read in as scalarsbut as row vectors and the computed trajectories are saved in the respective columnsof the matrices x and y.

Vector programming style:

function stability_v(g,x0,y0,tau)

Page 35: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 trajectoriesare combined in a matrix z. This kind of data storage enables matrix-matrix mul-tiplications in the for-loop of the explicit Euler method. Moreover, this function ismore flexible with regard to the input data. It accepts row as well as column vectorsfor x0 and y0 and checks if the length of initial vectors fit together. If the input datais defective, the program terminates with an error message on the screen (command

Page 36: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 35

error()). In addition to this, stability ext.m can be called with either four or sixinput 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. Notethat MATLAB saves the number of input arguments automatically in the variablenargin when calling the function. Finally, the plotting routine is extended in the waythat 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

Page 37: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 36

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 % provides initial x-values as row vector

x0=x0’;

end

[p,q] = size(y0);

if q == 1 & p ~= 1 % provides initial y-values as row vector

y0=y0’;

end

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

Page 38: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 37

−1.5 −1 −0.5 0 0.5 1 1.5−1.5

−1

−0.5

0

0.5

1

1.5

x

y

Asymptotically stable fixpoint for g= 1, tau= 0.1

−5 0 5−5

−4

−3

−2

−1

0

1

2

3

4

5

x

y

Instable fixpoint for g= −1, tau= 0.1

−1.5 −1 −0.5 0 0.5 1 1.5−1.5

−1

−0.5

0

0.5

1

1.5

x

y

Asymptotically stable fixpoint for g= 1, tau= 0.001

−5 0 5−5

−4

−3

−2

−1

0

1

2

3

4

5

x

y

Instable fixpoint for g= −1, tau= 0.001

−0.2 0 0.2 0.4 0.6 0.8 1 1.2−0.4

−0.2

0

0.2

0.4

0.6

0.8

1

Asymptotically stable fixpoint for g=1tau=0.1 (dashed), tau=0.001 (solid)

0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8−4.5

−4

−3.5

−3

−2.5

−2

−1.5

−1

−0.5

0

Instable fixpoint for g= −1tau=0.1 (dashed), tau=0.001 (solid)

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

Page 39: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 38

−3 −2 −1 0 1 2 3−2.5

−2

−1.5

−1

−0.5

0

0.5

1

1.5

2

2.5

x

y

Stable fixpoint for g= 0, tau= 0.1

−1.5 −1 −0.5 0 0.5 1 1.5−1.5

−1

−0.5

0

0.5

1

1.5

x

y

Stable fixpoint for g= 0, tau= 0.001

Figure 4.4: (stability ext.m) Analytically stable fixpoint (0,0) for g = 0 , but nu-merically 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 dependon the chosen step size. If the used step size is too large, an analytically stablefixpoint might be approximated incorrectly as numerically instable as visualized inFig 4.4. Hence, to rely on the simulation results, the underlying analytical conceptmust be always understood and – if possible – checked simultaneously. Otherwise, thenumerical outcome might lead to wrong conclusions.

? step size.m

MATLAB distinguishes between script and function files. In script files all variablesare globally defined, in functions only locally. Hence, script files provide all usedvariables as output to the workspace, and they cannot be called with certain inputarguments. Function files in contrast write out only the stated output arguments intothe workspace and can be called with and without input arguments as defined in thefile header. It depends on the demands whether a script or a function file is suitablefor a given task. In the following, script files are applied but the use of functions filesare certainly also possible. The command clear in the beginning of the script filedeletes 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

% ===========================================================

Page 40: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 39

clear

% initialization

A = [0 1 0; 0 0 1; -1 -1 -1]; % system matrix

h = [1 0.5 0.25 0.1 0.01 0.001]; % step sizes

xstart = 0; % underlying interval

xend = 2;

z([1,2,3],1) = [0 1 2]’; % 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); % explicit Euler method

end

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

Page 41: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 40

0 0.5 1 1.5 20

0.5

1

1.5

2

2.5

3

3.5

4y −− approximations (dashed), analytical solution (solid)

x

y

0 0.5 1 1.5 2−0.5

0

0.5

1

1.5

2

2.5

31st derivative −− approximations (dashed), analytical solution (solid)

x

y

0 0.5 1 1.5 2−4

−3

−2

−1

0

1

22nd derivative −− approximations (dashed), analytical solution (solid)

x

y

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

Page 42: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 41

The plotting routine in step size.m generates three figures for y , y ′ and y′′ respec-tively, cf. Fig 4.5. Whereas the approximations are visualized as black dashed lines, theanalytical solution is given as blue solid line. For the plot of the analytical solution, avery 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 thecommand subplot() in step size ext.m. Each subwindow visualizes the solutions ofone function, y , y′ and y′′ , such that their run is easy to compare, cf. Fig 4.6. For theplot 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 andlabels the x-axis, but it also changes the range of the axes. Hence, the commandaxis([xmin,xmax,ymin,ymax]) is applied to zoom into the region of interest. Ex-planations are included into the graphics at position (xtext,ytext) by means of thecommand text(xtext,ytext,’explanation’).

Used build-in functions: subplot(), ezplot(), axis(), text()

0 1 20

0.5

1

1.5

2

2.5

3

3.5

4

x

−cos(x)+2 sin(x)+exp(−x)

0 1 2

0

0.5

1

1.5

2

2.5

3

x

sin(x)+2 cos(x)−exp(−x)

0 1 2−4

−3

−2

−1

0

1

2

x

cos(x)−2 sin(x)+exp(−x)

numerical −−

analytical −

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

Page 43: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 42

% 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]; % system matrix

h = [1 0.5 0.25 0.1 0.01 0.001]; % step sizes

xstart = 0; % underlying interval

xend = 2;

z([1,2,3],1) = [0 1 2]’; % 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); % explicit Euler method

end

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])

Page 44: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 thenumerical approximation. The explicit Euler method is consistent of order p = 1 andfor the given linear system with Lipschitz-continuous right-hand side also convergentof order p = 1 . Hence the numerical approximations converge towards the analyticalsolution 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 predator-

% prey 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; % scalar-valued initial values

yRK(1) = 30;

xE(1) = xRK(1);

yE(1) = yRK(1);

Page 45: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 predator-

% prey model (algorithm in vector form)

% ===========================================================

clear

Page 46: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 45

% 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 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

Page 47: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 46

50 100 1500

20

40

60

80

h = 1

50 100 1500

20

40

60

80

h = 0.5

RK Euler

50 100 1500

20

40

60

80

h = 0.1

50 100 1500

20

40

60

80

h = 0.01

Figure 4.7: (euler vs rk ?.m) Comparison of explicit Euler and classical RK-approximations for different step sizes h .

All script files euler vs rk ?.m place the legend in the second subwindow in the firstrow according to the if-condition around the legend() command. To change itsposition 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 thegiven predator-prey model of the task. In contrast, the Runge–Kutta and Eulermethod in euler vs rk ext.m can cope with variable models, since the predator-preymodel is defined independently in the separate function file f pp.m which is called byeuler vs rk ext.m and easy to modify and to adopt to other models. Calling otherfunctions enables more flexibility and clearness in the program, but the price one oftenhas 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)

Page 48: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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)

Page 49: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 classicalRunge–Kutta method of order p = 4 . The consequences of this difference can be seenin Fig 4.7. The Runge–Kutta method yields the correct approximation already for arelatively large step size, i.e. h = 1 , whereas the Euler method requires a step size ofh = 0.01 for the same result. Hence, the Euler method needs 100 steps instead of 1in the Runge–Kutta method to provide the same accuracy. Comparing the operationsperformed in one step, the Runge–Kutta method is obviously more costly due to thecalculations of the different levels ki , i = 1, ..., 4 , but definitely not as costly as 100simple Euler steps. Consequently, the practical use of the higher-order Runge–Kuttamethod 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; % initialization of flag as x not found

w = sort(v);

n = length(w);

% 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

Page 50: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 49

if x == w(mid) % check of x and middle point

flag = 1; % x-value found

elseif x < w(mid) % otherwise partition of w

w = w(1:mid-1);

else % x > w(mid)

w = w(mid+1:n);

end

n = length(w); % update of length

end

The binary search algorithm is an every elegant and efficient way to search for an ele-ment in a given vector without applying any fancy MATLAB build-in functions. It isexclusively based on the recursive division of the given vector which can be straightfor-ward implemented by a while-loop. However, using build-in functions, in particularlogical operators, a search routine could look like exemplified in search matlab.m andsearch 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 combinationwith 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

Page 51: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 ex-emplifies a sorting algorithm that is based on the idea of the binary recursions, seesearch 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; % default position of xc in sorted s

flag = 0;

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

while (flag == 0) & (m > 0)

mid = round(m/2);

Page 52: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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’; % return of same-sized s as x

end

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

Page 53: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 byhelp of the implicit Center-point rule and meets therefore the demands of the exercisetask. 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 isrealized. The Van-der-Pol equations and their related variable parameters are storedindependently in the ODE-file vdp.m. Apart from the derivative, vdp.m might providethe initial values including options (like error tolerances, step size control etc.) and

Page 54: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 53

the Jacobian matrix by using the switch command for varying flag inputs. Style andstructure of vdp.m is typical for MATLAB ODE-files such that every build-in solvercan 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 withthe default values. Alternatively,

[t,z] = ode23s(’vdp’,[],[],[],mu),

then time interval, initial conditions and options are taken from the init routine ofthe 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);

Page 55: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 dy/dt = f(t,y).

varargout1 = f(t,y,p1);

case ’init’ % Return [tspan,y0,options].

[varargout1:3] = init;

case ’jacobian’ % Return Jacobian matrix df/dy.

varargout1 = jacobian(t,y,p1);

case ’initial’ % Return [tspan,y0,step,tol].

[varargout1:4] = initial;

otherwise

error([’Unknown flag ’’’ flag ’’’.’]);

end

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

Page 56: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 55

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;

0 5 10 15 20−15

−10

−5

0

5

10

15

t

Van−der−Pol Equation, µ=10

z1

z2

−3 −2 −1 0 1 2 3−15

−10

−5

0

5

10

15

z1

z 2

Van−der−Pol Equation, µ=10

orbit initial pointfixpoint

Figure 4.8: (implicit ext.m) Van-der-Pol equations for µ = 10 . Left: componentsz1 , 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 non-linear 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.

Page 57: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 56

0 0.5 1 1.5 2

x 104

1

2

3

time steps

itera

tion

step

s

Iteration steps in Newton method

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

Error Tolerance Numerical Jacobian Analytical JacobianCPU-time (sec) # flops CPU-time (sec) # flops

10−8 25.28 3 839 862 23.57 1 608 66310−3 22.73 2 056 484 22.77 1 460 723

Table 1: (implicit.m) Number of operations and computation time for solving theVan-der-Pol equations by means of the Center-point rule with the values of the exercisetask, in particular step size h = 10−3 .

However, the effort of the method depends on the desired accuracy of the Newtoniteration, since the number of iteration steps performed in the Newton algorithm isdetermined by the set error tolerance. To reach a high accuracy of tol=1e-8, two stepsare generally required per time step, cf. Fig 4.9. For a rougher approximation withtol=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 ofthe 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 analyticallyreduces the number of function evaluations drastically but has hardly any influenceon the elapsed time. Instead, the CPU-time is dominated by the step size h which

ODE-solver Error Tolerance Step Size CPU-time #flopsRelTol AbsTol maximal

ode23s 10−3 10−6 2 (adaptive) 0.25 48 210ode15s –‖– –‖– –‖– 0.27 72 255ode23t –‖– –‖– –‖– 0.30 57 260ode23tb –‖– –‖– –‖– 0.30 58 266implicit —— 10−6 0.1 (fixed) 2.50 ∼ 500 000

implicit ext —— 10−6 0.1 (fixed) 6.00 ∼ 500 000

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

Page 58: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 57

can be concluded from Tab 2. The MATLAB build-in ODE-solvers have the greatadvantage of using an adaptive step size control such that they approximate the Van-der-Pol equations with fewer steps and hence faster than implicit?.m regarding thesame 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 thisexample. The functions implicit.m and implicit ext.m perform approximately thesame number of evaluations, but the function calls of vdp.m in implicit ext.m slowthe calculations down.

From the mathematical point of view, a implicit algorithm might sometimes be slowerthan an explicit one although using bigger step sizes and thus less steps for the inte-gration of the ODE. In such a case, the effort of solving the complex non-linear systemin 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)

% ===============================================================

% initialization

h = 1/25;

k = h;

x = 0:h:1;

y = 0:k:1;

m = length(x);

n = length(y);

p = m*n;

L = zeros(p,p);

u = zeros(p,1);

f = zeros(p,1);

Page 59: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 58

% 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), ...

Page 60: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 59

00.2

0.40.6

0.81

0

0.5

1−0.02

0

0.02

0.04

0.06

0.08

x

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

y

u

00.2

0.40.6

0.81

0

0.5

1−0.5

0

0.5

1

1.5

x

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

y

u

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 and2 on a regular grid with h = k = 4 · 10−2 , cf. Fig 4.10. By defining step sizes hand k in x and y -direction it is already designed to handle also irregular grids withconstant mesh. However, initializing smaller step sizes, e.g. h ≤ 10−2 , k ≤ 10−2 ,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 respectivedirections, i.e. m = h−1+1 , n = k−1+1 , small step sizes imply fine resolution and lotsof grid points (in total: p = m n ). Hence, the finite difference matrix Lh,k is of sizep × p . In fd.m the command L = zeros(p,p) requires the storage of all components.Taking h = k = 10−2 yields # components = 10 8 of which maximal 5p = 5 · 104 arenon-zero due to the applied 5-point difference stencil. Half of the information to bestored 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-zeroentries in the sparse mode. This leads to a drastical reduction of memory demands andto the avoidance of arithmetic operations on zero entries. Thus, the efficiency in storageand time is increased which makes feasible the solution of significantly larger problemsthan would otherwise be possible. The sparse mode can be incooperated in fd.m bythe 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 shouldtherefore never be underestimated. Sparse matrices are stored as linear arrays of theirnon-zero elements along with their row and column indices, but can be handled inthe same way as full matrices, since algorithmic operations and (most) MATLABbuild-in functions work independently of the storage mode. The functions full() and

Page 61: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 60

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

Full: operations on full matricesFull: S+F S*F S\F F\SSparse: S+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, re-spectively

speye, sparse, spones, sprandn, spdiags .The versatile function sparse() creates not only a sparse zero matrix of size m × nby sparse(m,n) or converts the full matrix F into a sparse one by sparse(F), butalso permits the generation of a sparse matrix via listing its non-zero elements. Takefor 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 lowersubdiagonal, d on the main diagonal and f on the second upper subdiagonal. Notethat 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 thefollowing tridiagonal system of equations stemming from a second difference approxi-mation 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 theextended version fd ext.m the Dirichlet boundary values problems are solved on a fineirregular grid with varying step sizes hi , kj . Hereby, the sparse difference matrix isassembled 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

%

Page 62: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 61

% 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;

Page 63: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 62

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;

Page 64: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 differencemethods, since it enables the finer resolution of critical domains of special interest. Incontrast, regions where the solution does not vary much can be discretized roughlywhich saves memory storage and reduces the CPU-time. Irregular grids are known asadaptive meshes (cf. Fig 4.11). Irregular grids changing over time are – under the topicadaptive mesh refinement – a very popular field of recent research since its reasonableapplication is necessary for efficient and accurate numerical simulations of most real-life problems, e.g. blowing up of air-bags, filling of car petrol tanks, manufacturing ofglass.

Page 65: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 64

00.2

0.40.6

0.81

0

0.5

1−0.02

0

0.02

0.04

0.06

0.08

x

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

y

u

00.2

0.40.6

0.81

0

0.5

1−0.5

0

0.5

1

1.5

x

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

y

u

00.2

0.40.6

0.81

0

0.5

1−0.02

0

0.02

0.04

0.06

0.08

x

Solution of Poisson Problem 1 for varying step sizes

y

u

00.2

0.40.6

0.81

0

0.5

1−0.5

0

0.5

1

1.5

x

Solution of Poisson Problem 2 for varying step sizes

y

u

Figure 4.11: (fd ext.m) Poisson equation on fine regular, h = k = 10−2 , (top) andirregular 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)

Page 66: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 % random walk

r=rand(1);

if r<=p

Pt(j)=Pt(j)+u;

else

Pt(j)=Pt(j)-d;

end

end

end

% 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

Page 67: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 66

−200 −150 −100 −50 0 50 1000

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

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

observables mean (monte carlo)mean (analytical)

−400 −300 −200 −100 0 100 200 3000

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

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

observables mean (monte carlo)mean (analytical)

Figure 4.12: (random walk.m) Probability density distribution of the observables for10 (left) and respectively 100 (right) Monte–Carlo simulations.

0 1 2 3 4 5

x 104

0

0.2

0.4

0.6

0.8

1

1.2

1.4

1.6

1.8

2

Error for n Monte−Carlo simulationsP0=0, p=0.5, u=d=10, t=10

n

erro

r

Figure 4.13: (random walk.m) Deviation between analytical and numerical expectationover number of Monte–Carlo simulation runs.

The probability of the random walk going up or down is incooperated in the programby help of the if-condition. Since r=rand(1) is a random number, in particulara uniformly distributed deviate in the interval [0, 1] , it can be compared with theprobability p . Take for example P(Ψi = u) = 0.6 , i.e. the increment in the randomwalk is positive with 60%, then the command if r<=p checks whether or not r lies inthe elected 60% of the unit interval, here [0, 0.6] . Alternatively, one might choose another 60%-fracture for the comparison, e.g. [0.2, 0.8] or [0, 0.2] ∪ [0.6, 1] .

Mathematical comments:In Monte–Carlo simulations, several representants of a random process are computedand then averaged. The quality of the numerical expectation depends on the numberof observables: the bigger the sample, the better in general the approximation asvisualized in Figs 4.12, 4.13. The probability density distribution approximates a

Page 68: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 67

normal distribution and numerical and analytical mean coincide. Anyhow, due tothe involved stochastics, there is no deterministic relation between the error and thenumber of simulations, as Fig 4.13 clearly shows. Even for lots of repetitions, arelatively big error might arise, take for example n = 3·104 , error |µanal−µnum| ≈ 0.5 .

? integration.m

Writing longer and complex programs, a well-structured m-file management becomesnecessary. Instead of one huge file, the program is split into smaller self-sustainingblocks / algorithms being realized in corresponding function files that are called by asuperordinate organizing script (function) file. This hierarchy of files enables an easyand separate handling and debugging. Moreover, different subordinate files can beflexibly linked together such that a variety of comparison and visualization routinesdependent on task and interests can come up. However, one can certainly also exag-gerate the generation of subordinate files such that a supposed clear-ordered structuregives way to a real mess. Every programmer has his/her personal preferences andstyle in structuring and commenting files. Find your own way, but be aware that youor maybe your friends want to work with your program in future. This presupposesannotation.

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

Page 69: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 flag’’’flag’’’.’]);

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);

Page 70: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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;

Page 71: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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’]);

Page 72: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 71

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

end

0 0.5 1 1.5 2−2

0

2

4

6exp(x)−2

2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.80

0.2

0.4

0.6

0.8

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

ObservablesMonte−CarloTrapezoid Simpson exact

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

0 20 40 60 80 1002.2

2.4

2.6

2.8

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

0 20 40 60 80 1000

0.2

0.4

0.6Corresponding errors

Monte−CarloTrapezoid Simpson

Figure 4.15: (integration.m) Integral values and errors in dependence of numberof grid points in the quadrature rules and respectively the number of Monte–Carlosimulations.

Page 73: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 72

In the script file integration.m, the function under consideration is initialized asstring 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 iscertainly also imaginable, then the command feval() is used for the evaluation.

Mathematical comments:In contrast to numerical differentiation, numerical integration is a very difficult prob-lem since it is ill-posed. But its need is realized in a lot of simulations, e.g. for theassembly of the stiffness matrix in finite element methods. Quadrature rules do a goodjob, e.g. Newton–Cotes formulae, but in particular the quality of Gaussian quadraturerules 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 inFig 4.15. Monte–Carlo simulations could also be used for the integration but they areundoubtedly not a reliable alternative. The errors are comparatively high and obeyno 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);

Page 74: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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);

Page 75: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

4. Possible Implementations and Further Comments 74

0 5 10−5

0

5

10

15

20

25

30Data fitting

data linear quadratic cubic exponential

0 0.5 1 1.5 20

5

10

15

20

25

30

35

Absolute error over lp−norm

p (p=0: max−norm)

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); % l_1-norm

enorm(2,1:no_fit) = sqrt(sum(e.^2)); % l_2-norm

enorm(3,1:no_fit) = max(e); % max-norm

norm = repmat([1;2;0],1,no_fit);

% 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);

Page 76: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 fitindependent of the chosen lp -norm (cf. Fig 4.16).

In general, data fitting is of special interest for engineering or scientific applicationsto give a feeling and deeper understanding for the relation between different param-eters resp. the influence or dependence of one parameter on the other. Based on thelimited number of available experimental data (in discrete form), curve fits provide acontinuous mathematical model, i.e. a mathematical description of real-life.

Page 77: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

5. Test Questions and Answers 76

5 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 AB−1 and left division A \ B means A−1B .

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 nOutput: 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)x′(t) = λx(t), x(0) = x0

Solve the given initial value problem in the time interval t ∈ [0, 20] for variable initialvalue x0 (scalar), parameter λ (scalar) and step size h (scalar) by means of theexplicit Euler method. Plot the trajectory as red solid line.

Solution:function euler(x0,lambda,h)

Page 78: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 to253.

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.

8. Create the matrix B =

(

A dT

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)x′(t) = λx(t), x(0) = x0

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

Page 79: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 descendingorder.Input: vector vOutput: 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

Page 80: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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 4nnon-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 1with increment 2 . Create a vector c of same length as b whose entries are thesame 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 thirdlower subdiagonal and c on the second upper subdiagonal.

Page 81: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

5. Test Questions and Answers 80

6. Which elements of a, b, c are missing in the diagonals of T?a 2 none 2 first ... (number) 2 last ... (number)b 2 none 2 first ... (number) 2 last ... (number)c 2 none 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 between0 (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); ora(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); ora = 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

u′′(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 thefigure a title.Implementation:Input: number of grid pointsOutput: • u on all grid points (including boundary points)

• grid points• mesh size (step size)

Page 82: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

5. Test Questions and Answers 81

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 andadditionally plots all points of S as black stars, the point (xP , yP ) as blue circle ofsize 10 and its nearest neighbor (xN , yN) as red cross of size 10.Implementation:Input: • point as column vector P = (xP , yP )T

• ”set” matrix S =

(

x1 x2 ... xm

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); % Euclidean distance

[d,pos] = min(D);

N = S(:,pos);

% visualization

plot(S(1,:),S(2,:),’k*’);

Page 83: SCIENTIFIC COMPUTING WITH MATLAB - pudn.comread.pudn.com/downloads143/ebook/624396/Scientific Computing.pdf · SCIENTIFIC COMPUTING WITH MATLAB Dr. Nicole Marheineke TECHNISCHE UNIVERSITÄ

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