Professional Documents
Culture Documents
J. Berns-Müller
1 Introduction 4
1.1 General Remarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.1 What is Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.2 Why might Matlab be useful . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 First Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.1 Demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2.2 Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1
CONTENTS 2
4 Conditional Statements 22
4.1 Branching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
4.1.1 Branching with if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
4.1.2 Branching with switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4.1.3 Searching with find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.2.1 The fixed loop for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.2.2 The conditional loops while . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
7 Graphic 39
7.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
7.2 The plot command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
7.2.1 plot with one argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
7.2.2 The plot command using two arguments . . . . . . . . . . . . . . . . . . . . 41
7.3 Movies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
7.4 Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
7.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
9 Numerical Methods 49
9.1 Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
9.2 Quadrature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
9.3 Probability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
9.4 Other functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
9.5 Ordinary differential equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
9.6 Partial differential equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
CONTENTS 3
9.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
10 Examples 55
10.1 Random number generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Chapter 1
Introduction
4
CHAPTER 1. INTRODUCTION 5
femlab Finite Element Software Packet for numerical approximations of Partial Differential Equa-
tions
LAPACK Numerical methods in Linear Algebra (direct methods)
SCALAPACK Numerical methods in Linear Algebra for large problems (direct methods)
ARPACK Numerical methods in Linear Algebra (iterative methods)
NAG Commercial library of Numerical Methods (Fortran)
Petsci Freeware library of Numerical Methods (C++/MPI)
(LAPACK and ARPACK are part of Matlab)
>>
Many little problems can be easily solved directly from the prompt. However when problems
are more complex we will see later how we can write scripts and functions. But we start with the
Matlab prompt.
The probably most important command at least when working with the Matlab shell is
the ”exit”-command. Otherwise the command ”help” will be one of the most frequently used
commands, as the online help function is extremely helpful.
CHAPTER 1. INTRODUCTION 6
1.2.1 Demo
To get started Matlab provides several demos demonstrating how Matlab works ranging from
introductory material on datatypes up to solving partial differential equations.
To start working with Matlab type
>> demo
>>
followed by the [Return]-key (Matlab starts to perform only after the return key has been
pressed). As done above we will present Matlab-code as it should be typed in on the com-
mand line. In some cases we will also illustrate the resulting effect but mainly we leave this to the
user to explore.
Now as the demos have opened up please have a go at them.
1.2.2 Help
As noted, the ”help” command is very useful. With
>> help
>>
one gets an overview of further help topics which then can be accessed for example by typing
>> help general
>>
Also to all build-in functions there is usually quite precise information available, for example,
for the ”luinc” function which calculates an incomplete LU-factorisation. To get the corresponding
help simply type
>> help luinc
>>
Further one can get the source code of many such function by typing
>> type GMRES
>>
However, there are build-in functions and further functions. For the core build-in functions the
command ”type” will not work, so ”type luinc”, and ”type GMRES” differ greatly.
1.3 Literature
There are several books for getting started with Matlab or programming with Matlab and
specially many books on how to use additional packages. This course together with the online help
should provide a good start for working with Matlab. Hence we do not suggest to buy one of the
following books, however in case you like to have an additional source these are recommendable
books.
Getting started:
Rudra Pratap Getting Started with Matlab (Oxford)
Duane Hanselman & Bruce Littlefield Mastering Matlab (Prentice Hall)
The Matlab guide on how to use the graphic tools is also recommended, as there are so many
graphical commands that we can not cover them all, and specially not all their options. However
in Chapter 7 we discuss the most import points.
1.4 Exercise
In each chapter we provide a couple of exercises, which should foster the understanding of Matlab.
Aufgabe 1.1 Start a Matlab-session, clear all windows but the command window and type the
command ”help help”.
Aufgabe 1.2 Please type the commands ”help” and ”help ops”. (Here you find a summary of all
the Matlab math operators.)
Why does the second command cause an error? What is the effect of the command ”clear”?
Aufgabe 1.4 Please test the ”Traveling Salesman” demo, which you can activate by calling ”de-
mos” and opening the section Other Demos or simply by typing ”travel”. What is the effect of
”help travel” and ”type travel”?
Aufgabe 1.5 The purpose of this exercise is to show how easily mathematical problems can be
solved in Matlab.
Given the initial value problem
2
d
x(t) = −x(t) x(0) = 1.
dt
(The last line plots the error between the numerical approximation and the exact solution.)
Chapter 2
2.1 Basics
The basic datatypes in Matlab are
Here we consider just matrices, the remaining three basic datatypes will be discussed in Chap-
ter ??. Matlab has a variety of further datatypes however they are neither essential nor are
they needed explicitly in standard applications. The reason for the later is based in the automatic
datatype conversion and the automatic memory allocation. However if you like to learn more about
other datatypes type ”help datatypes”.
Throughout this script we use the above form to highlight Matlab-code as written to the command
line.
a Variable names: Here a is a name of a user defined variable. Variable names start with a
letter and may contain numbers and the underscore. Matlab itself distincts between small
and capital letters, however if your system does not some internal Matlab variables and
functions might not be case sensitive.
= Assignment: With assigning a value to a variable all previous information of this variable such
as datatype, size and content are lost. The new variable a has now the type, size and content
according to the right hand side. (The comparison operator for equality is ”= =”.)
; and , End of a command: The semicolon at the end of a command first of all marks the end of
the command and secondly suppresses the result. If you like to mark the end of a command
but like to see the result you can use the comma or the [Return]-key. In case you like to write
more than one command into one line you need to use either the comma or the semicolon to
separate the commands.
8
CHAPTER 2. NUMBERS AND MATRICES 9
>> a = 1; b= 2, c=3; d=4
>>
The datatype matrix encloses numbers and arrays of numbers. Integer, rationals, reals and
complex numbers are all numbers and hence of type matrix. So
>> a = 1
>> b = 1/3
>> c = 1.2e2
>> d = 1+1i
>> 2+i
>> 3+j
>> 1.5e-3
>>
are all of type matrix. As one can see from above there are several ways to define complex
numbers, so ”i”, ”j” and ”1i” are all the same number, the imaginary unit. Only the last form is
recommended as the first two forms are contents dependent, as the following example shows
>> clear
>> i
>> i=1.2
>> i
>> clear i
>> i
>>
The output format depends on the values and a general output format. The standard output
format is short. For more on the output format see ”help format”. Changing the output format
has now effect on the internal working accuracy.
Further the two values N aN (not a number) and inf (infinity) are treated as special numbers,
so that one can do calculations with inf and N aN , however the result is likely to be N aN .
2.2.2 Matrices
>> A = [1,2,3;4,5,6;7,8,9;10,11,12];
>>
[ ] Square brackets: Matrices are defined by a pair of square brackets. The size of the matrix is
given by the use of comma and semicolon. The comma is used to separate two columns and
the semicolon to separate two rows. As above the definition has to be row wise not column
wise.
The semicolon within the square brackets has a different meaning than the semicolon at the
end of a command.
>> A
ans =
1 2 3
4 5 6
7 8 9
10 11 12
>>
CHAPTER 2. NUMBERS AND MATRICES 10
As all values in the matrix are integers the matrix is presented as a matrix of integer. In general
the matrix is presented as a matrix of that class of numbers which contains all numbers presented
in the matrix and where there is at least on matrix entry of this class.
>> A = [1,1.1;3,4]
>> B = [1,1i;3,4]
>>
As matrices are the main object to deal with in Matlab there are plenty of further possibilities
to define them. In the following we consider a few of them.
>> A=[1,2,3;...
4,5,6;...
7,8,9;...
10,11,12];
>>
... Continuation points: The triple dot allows to continue a command on the next line. This can be
used to help with extremely long expressions and to improve the readability of the command.
2.2.3 Vectors
Column vectors are n × 1 matrices, similarly for row vectors
>> a=[1,2,3];
>> b=[1;2;3];
>> c=1;
>> d=[1:5];
>> e=[2:-0.1:1.05];
>>
In order to access a list of matrix elements simultaneously, say (1,2), (1,4), (2,1) and (3,3), we
need the corresponding single indices which are provided by the function ”sub2ind”. The opposite
action is given by ”ind2sub”.
>> I=[1,1,2,3];
>> J=[2,4,1,3];
>> f=A(sub2ind(size(A),I,J));
>>
Similar to accessing multiple entries of a matrix we can also change multiple entries of a matrix
simultaneously
CHAPTER 2. NUMBERS AND MATRICES 12
>> A(4,1) = 0;
>> A(3,2) = -1;
>> A(sub2ind([3,4],I,J)) = -2
>>
Simultaneous actions are much faster than their corresponding sequential ones. This is due
to two effects. First, Matlab interprets each line before it evaluates it, and the simultaneous
statement needs only one interpretation. Second, the blas routines used within Matlab allow fast
actions of of vectorized expressions.
The matrices B and C are identical, however the matrices D and E differ in their (1, 1) element.
(While the use of .0 is mathematically correct for real matrices, often the use of 0 helps to get the same
code working for real and complex matrices!)
2.5.1 Constants
Some important constants
Name Command Value
π pi 3.1415. . .
e exp(1) 2.7182. . .
machine precession eps 2.22 . . . · 10−16
CHAPTER 2. NUMBERS AND MATRICES 14
In contrast to the previously noted functions the following ones interpret the given argument either
as a vector or as a matrix
norm(a) 2-(matrix-/vector-)norm norm(a, p) p-(matrix-/vector-)norm
(The commands ”permute” and ”permute” are not the standard math permutations but they
permute the coordinates.)
CHAPTER 2. NUMBERS AND MATRICES 15
2.6 Exercises
Aufgabe 2.1 Please work through the Section 2.1 to 2.4 and make sense of the answers Matlab
provides.
Aufgabe 2.5 Plot the sine-function for the values between 0 and 2π. (You may use the ”plot(x,sin(x))”-
command.)
Aufgabe 2.6 Define 3 × 4 a matrix with all entries zero and one with all entries equaling one by
applying the Matlab-functions ”zeros” and ”ones”. Control the size of these matrices with the
command ”size”.
Aufgabe 2.7 Design a 10 × 5 and a 12 × 6 matrix with random elements. To get a third matrix
take the first 25 elements of the first and the last 15 elements of the last such that the third matrix
has in its last entries those from the first. The third matrix shell have the format 5 × 8.
Aufgabe 2.8 Given our standard matrix A = [1, 2, 3; 4, . . . , 12];. What is the effect of ”b =
diag(A)” and ”B = diag(b)”.
Chapter 3
3.1 General
Scripts and functions are used to reuse larger program sections. Additionally they allow debugging.
The essential difference between scripts and functions is their effect on the variables in the workspace
(that are all currently defined variables). Functions work only on local variables, that are variables
defined within the functions. Hence they need an interface to get input data and to place the results.
In contrast a script works on the global data, so all previously defined variable are accessible (can
be assessed, changed, deleted) and are afterwards available in the form the script has left them.
The advantage of functions is that they leave the variables in the workspace unchanged, the
disadvantage is they need more memory as variables transfered to the functions are implicitly
copied. The situation with scripts is the opposite.
3.2 Editor
In case the editor is not open it can be opened using the File-menu (”File→New→ M-file” or
”File→open”). Additionally one can use the command line
>> edit
>>
or respectively
>> edit name
>>
The latter action opens the editor with the file ”name”. However, name needs to end on .m to
show that this is an ”M-file” to be used within Matlab.
Of course one can use alternative editors, for example vi, pico and emacs under Unix and Linux or
notepad under Windows.
16
CHAPTER 3. SCRIPT AND FUNCTION FILES 17
5 who
6
and save the file as script1.m. Saving the file can be achieved by using the ”File”-menu and then
”Save as”. Now we switch back to the command window and enter
>> A = [7]
>> B = 1
>> Script1
>> A
>> B
>>
Please note that we saved the file as script1.m and called it as script1, so we dropped the ”.m”.
Just a note on the style of your scripts. By now you should have used the ”help”-function to
get information on Matlab build-in functions. In order to provide the user some help on the use
of your scripts and functions you can write some comments at the top of your file. The first line
in known as H1-line and enables keyword search using the ”lookfor” command. So in this line you
should place some useful keywords. All leading comment lines, that are lines which start with a
comment, are interpreted by the ”help” command as help text. The leading ”%” will be deleted
by the help command.
So our script should read
1 % Script-file: Definition of a matrix
2 % This file illustrates the structure a script file should have.
3 % For this purpose this file defines a variable ”A” containing
4 % a matrix. Further this script deletes the variable ”b”.
5 A=[1,2,3;4,5,6];
6 clear b
7
which we save as script2.m. In order to see the effects of these changes we switch back to the
command window and type
>> clear
>> A
>> Script2
>> A
>> lookfor Matrix
>> help Script2
>> type Script2
>>
When modifying above file (downloadable from the Matlab course web page) one needs to change
the names, course and sheet number accordingly, and insert the solutions at the appropriate points.
After saving the file, say as tutorial1.m, the script needs to be executed by which another file
is created having your name and the sheet number as name of the file, so in the case above
”Sharp Bob 1”.
In case you are not happy with your answer, modify tutorial1.m, save again and run again
”tutorial1”.
The thus created file, here ”Sharp Bob 1”, is to be handed in.
Saving this as plotsin.m we can now call ”help plotsin”, ”plotsin(5)” and ”plotsin(100)”.
Notation Capital letters: In order to better distinct between variable names and standard text
within the help statements (leading comment lines) one usually writes the name of the func-
tion and the variable names with capitals. With respect to the variable names this is fine,
however with respect to the function name this is somewhat problematic, as the name of the
Matlab function is case sensitive. Further note that the name of the function as written
within the file is unimportant, the name of the file is what matters!
function Definition of a function: The Matlab command ”function” in line 8 defines this file
as a Matlab function. Basically the function declaration consists of five parts, first the
function command, second the output list, third the assignment sign (=), fourth the name
of the function and fifth the input list of variables.
function out-list = f-name (in-list)
As noted above the name of the function is for a single function in a function file not impor-
tant. What matters for Matlab is the name of the file, here plotsin.m. The name of the
function follows the convention for the names of variables, starting with a letter followed up
by any combination of letters, numbers and the underscore, ” ”.
Parameter lists Input and output lists: If the out-list consists of a single variable, then the name
of the variable is enough. Otherwise the out-list needs to be enclosed by a pair of square
brackets. The in-list requires always round brackets, independent of the number of elements.
Any of the two list might be empty, then the function does not require any input variables
and it certainly does not return any value.
The name of the variables being used in the function definition and the code might differ
from the name being used in the help area, however this might upset people checking your
code. A short but meaning full name helps understanding your code.
As the names are allowed to differ to their use outside, the position within the in-list and
out-list are important.
Variable parameter Matlab allows the use of variable input and output parameter lists. Ac-
tually man build-in function react differently depending on the number of parameters passed
to the function, for example see plot, and asked as a return, for example see lu. In order to
allow a variable parameter length, the last element in the in-list needs to be varargin and
varargout respectively for the out-list. Then the variables nargin and nargout are defined and
contain the number of variables the user passed on to the function or respectively required
as a return.
3.6 Inline-Functions
There are three ways to define simple math functions, first we could write an M-file, we can use
the ”@” command or we could use the ”inline” command
>> q=@(x)x. b2-3
>> q(3)
>> x=[-3:0.1:3];
CHAPTER 3. SCRIPT AND FUNCTION FILES 20
>> y=q(x);
>> fzero(q,3)
>> q(fzero(q,3))
>> plot(x,y);
>> hold on
>> plot(a,0,’r*’);
>> hold off
>> p = inline(0 x. b2-30 ,0)
>> p(pi) - q(pi)
>>
@ Function definition: The command ”@(parameter list) formula” provides an easy way to define
simple functions. Here the parameter list consist out of those variables one likes to pass on
and the formula is a math formula as it could be written to the Matlab prompt.
(The ”@” command is not available on all machines and platforms)
inline Function definition: There are several ways to define an inline function using the command
”inline”, see ”help inline”.
fzero Finding zeros of a nonlinear function: The command ”fzero(function,initial)” tries to detect
a value X for which the function is zero. In case initial is a scalar, the function starts from
this value, however if initial is a set of two values, say initial = [a, b] then fzero requires that
the function, say f (x), satisfies f (a) ∗ f (b) < 0. In this case fzero will always succeed and
determine a value x.
hold Freezing current plots: The command ”hold on” freezes the current plots, so that the following
plotting commands are added to the current one. To reverse the freezing type ”hold off” or
simply clear the graphic window with ”clf”.
3.6.1 Subfunctions
Within one M-file we can define several functions, however from outside we can call only the first
one, the others are only accessible from inside this M-file.
We can also pass on functions as an argument. This can be achieved in two ways. First, we can
provide the name of a function and then call the function inside the file using the ”feval” command.
More elegant is to pass on the function itself. Here the inline functions are quite useful.
1 % [X,Y] = approx min(F,A,B)
2 % plots the function F in the interval [A,B] and
3 % approximates the minimum in [A,B].
4%
5 function [x,y] = approx min(fct,a,b)
6 X = [a:(b-a)/100:b];
7 Y = feval(fct,X);
8 [y,ind] = min(Y);
9 x = X(ind);
10 present result(X,Y,x,y);
11 return
12
13 %%%
14 function [ ]=present result(X,Y,x,z);
15 plot(X,Y,0 −0 );
CHAPTER 3. SCRIPT AND FUNCTION FILES 21
16 hold on;
0 0
17 plot(x,z, ∗g );
18
(The last argument in the ”plot” command forces Matlab to use green stars for this set of data.)
Saving above code as Amin.m we can type
>> Amin(q,-2,pi)
>>
3.7 Debugging
Standardly when programming one makes mistakes in the code and finding them afterwards can
be a tantalizing task. Here Matlab provides a wonderful environment for debugging.
The debugger is part of the editor window, see the debug menu. Setting of break points, that
are points where Matlab stops the execution of a file, can be done by pressing the left mouse
button on the corresponding line number in the editor window. By doing so Matlab sets a red
point in front of this line to indicate that a break point is set. Another click and it is cleared.
The execution of a script file can be started directly from the editor window, while a function
file needs to be started from the command line.
Once a break point is reached the Matlab prompt in the command window chances to indicate
that the debugger stopped at a break point. The command window has the standard functionality,
however the current data available are those form the debugger. This implies that we can view the
values of all current variables, and can do some manipulations with them. From the first break
point on we can decide to go step wise or continue till the next break point, we can add and delete
break points as well.
3.8 Exercises
Aufgabe 3.1 Write a script for plotting the tangent and the hyperbolic cosine within one coordi-
nate system for the interval [−π/4, 0.1π].
Aufgabe 3.2 Implement the example from Section 3.6.1 and define a break point and execute the
file step by step.
Aufgabe 3.3 Clear all current variables in the workspace using ”clear”. Which use has the ”cd”
command? Write a small script, say ”fprintf(’Hello world’)”, and save it as ”cd.m”. What happens
now if you type ”cd” in the command window? Next type ”cd=1” and ”who”. What happens now
if you type ”cd” in the command window? Now type ”clear cd” and ”!rm cd.m”, what is the effect
of these two commands? (In case of a Windows machine exchange ”!rm cd.m” by ”!del cd.m”)
Chapter 4
Conditional Statements
4.1 Branching
Matlab has two branching commands, ”if” and ”switch”. Further we consider here the command
”find” which occasionally can be used instead of ”if” and ”switch” statements.
The ”if” command is followed up by a conditional statement enclosed in round brackets. Fol-
lowing the if command and the conditional statement, there can be as many Matlab commands
as the user wishes until the ”end” command which finishes the if statement. The block might
have several ”elseif (condition)” statements as the user likes, however care must be taken on their
ordering. Finally there might be one ”else” command. Any sub-block started by if, ifelse and else
can be followed by any number of Matlab commands and ends with the next elseif, else or end
statement.
As the block of
1 if (condition) commands
2 {elseif (conditions) commands }
3 [else commands]
4 end
5
can be viewed as command in itself, so we can employ an if statement within another one.
1 if (a>1)
2 fprintf(’a is larger than 1\ n’);
3 else if (a>-3 & a<-1)
4 fprintf(’a is between -3 and 1\ n’);
22
CHAPTER 4. CONDITIONAL STATEMENTS 23
5 else
6 fprintf(’Is a nowhere?\ n’);
7 end
8 end
9
The shifts being used in above manner have been placed to indicate the logical structure. While
both programs provide the same result they differ with respect to their number of if blocks. The
first example uses one (extended) block while the second one uses two (simple ones), an inner and
outer statement.
A condition is a boolean expression, that is, the statement is either true or false. In Matlab the
value for false is ”0”, any other value is considered as being true. The following boolean operations
are provided
∼a not a
a&b a and b
a|b a or b
and(a, b) a and b
xor(a, b) a and not b or b and not a
Additionally there are the operations ”a&&b” and ”a||b”. The logical meaning is the same for ”a&b”
as for ”a&&b”, similarly for ”a|b” and ”a||b”. In case of ”a&b” and ”a|b” both expressions a and b are
evaluated before the logical expression & or | is evaluated. Further these operations can be applied to
matrices a and b where a and b need to have matching size. In contrast ”a&&b” and ”a||b” can only be
applied to scalar variables and b is only evaluated if the value a has not lead to a decisive answer. So if a
is false, then b is not evaluated in the ”a&&b” condition, similarly for a true in the ”a||b” condition.
For a better understanding of the boolean operation check the following results
>> A=[0;0;1;1];
>> B=[0;1;0;1];
>> [A,B,A&B]
>> [A,B,A|B]
>> [A,B,A| ∼B]
>> [A,B,xor(A,B)]
>>
4.2 Loops
Here we have the ”for” and ”while” loops. In order to break up, stop and restart the loops Matlab
provides the commands ”break” ”continue” and ”return”.
Often loops can be avoided by vectorizing the command. Actually vectorizing Matlab com-
mands leads to much better (faster) performances than using loops instead. Nevertheless loops are
still important.
break immediate stop of the loop This command stops the loop immediately, so the remaining
commands in the loop are not executed and the loop condition is ignored. In case the loop
is enclosed in another or even several loops, only the inner most loop is stopped.
continue step over, continue: With this command the remaining commands in the loop are
ignored, Matlab goes back to the start of the loop and continues the loop with the next
cycle.
return exit M −f ile Strictly speaking this is not a loop command, however it gets almost only used
within a loop, especially in an inner loop if all loops should be stooped. As this command
aborts the execution of commands within an M-file the command should be preceded by
commands ensuring that the output variables are set accordingly.
The commands ”break”, ”continue” and ”return” can also be used within a for loop.
Occasionally implementation is hampered with a mistake and a loop does not stop by itself, then the
loop can be stopped from the command window by pressing the keys [Control] and [C] simultaneously.
4.3 Exercises
Aufgabe 4.1 Please carefully work through this section and execute the scripts.
Aufgabe 4.2 Write a function ”Fibonacci”. This function has one input variable an returns
all Fibonacci numbers up to the value of the input variable. Test your function by calling ”Fi-
bonacci(3)” and ”Fibonacci(41.2)”.
Aufgabe 4.3 Write a function ”fact”. This function has one input variable and in case the
variable is a positive integer it shall return n!. If the input value is not an integer an error message
would be fine. Test your function by calling ”fact(7)” and ”fact(9.1)”.
Aufgabe 4.4 Write a function ”euclid”, which should return the largest common divisor of two
input arguments. If the input variables are non integers or not enough input arguments have been
passed on to the function than an error message should be provided. Test your function by calling
”euclid(12,8)”, ”euclid(27,34)”, ”euclid(4)” and ”euclid(4.1,-3)”.
Chapter 5
Due to the automatic type conversion by Matlab we consider here only the four main data types.
We already discussed the data type matrix in Chapter ??. Here we discuss the datatypes
To get more information on other data types please use the help command, ”help datatypes”.
5.1 Strings
A string is a collection of letters, numbers and other signs usually all known as char enclosed by
single quotes, ”0 ”, for example ”’hello’”. Due to the automatic type conversion we do not need to
allocate memory nor do we need to define string variables. Some more examples for strings
>> A = [3, 4] % this is a matrix
>> A =0 hello world 0 % now A is a string
>> B = [0 hello 0 ,0 world 0 ]
>> B(1)
>> B(2)
>> B(1 : 5)
>>
The second assignment ”A=0 hello world 0 ” deletes the original variable A and a new one is created.
Hence the datatype and the context A previously had does not matter. Matlab allows easy access
to strings and several ways to concatenate strings. When concatenating two strings there is no
additional sign in between the two strings.
>> C =0 345 0
>> C(1)
>> C(2)
>> C(1) ∗ C(3)
>>
The output format is ambiguous, we can not see clearly whether the output from line two and
three are numbers are numbers or not, actually they are not, they are strings like C itself. With
”ischar(C(1))” we can check if C is a string.
While C(1) and C(2) return the strings containing the specific numerical characters, so of type
string, we obtain a numerical value with C(1) ∗ C(3). As multiplication is not a string operation
but a matrix operation the two values C(1) and C(3) are interpreted as being of type matrix and
there value is determined using the ASCII table.
The opposite effect occurs in
27
CHAPTER 5. OTHER DATA TYPES 28
>> D = [0 hello 0 ,59,45,41]
>>
Here the numbers 59, 45, and 41 are interpreted as characters getting the corresponding char again
using the ASCII table.
Explicit type conversion is more readable than the implicit conversion. Implicit type conversion
is bad style!! The explicit operations are ”double(A)” and ”char(A)”.
5.2 Structs
This datatype is frequently used by Matlab build-in functions, for example ”help luinc”, specially
for advanced options. The advantage of this datatype is it can carry various components which
have their own name, thus the ordering of the information is unimportant. For these component
names the standard name convention applies.
>> A.type=0 matrix 0 ;
>> A.size=[3,2];
>> A.content=[1,2;3,4;5,6];
>> A
>> A.type
>> A.content
>> B=struct(0 type 0 ,0 matrix 0 ,0 size 0 ,[3,2],0 content 0 ,[1,2;3,4;5,6]);
0 0 0 0 0 0 0 0
>> C=[struct( type , matrix , size ,[3,2], content ,[1,2;3,4;5,6]);...
0 0 0 0 0 0 0 0
>> struct( type , matrix , size ,[1,1], content ,0)];
>> C(2).content
>> C(1).type
>> C
>>
Matlab supplies the following routines to work with the datatype struct
struct(. . . ) creates a struct: See ”help struct” for specific information. Simply this can be used to
construct and simultaneously name some components if not all of this newly formed variable
and simultaneously initialize these components.
isfield(S,0 name 0 ) components test: tests if a certain component, name, is part of the struct S.
S=getfield(S,0 name0 ) Access: this is a more complicated form for ”S.name”, however in case of
programming with arbitrary and unknown options this is quite useful.
S=setfield(S,0 name0 ,wert) Assigning: this is a more complicated form for ”S.name=wert”.
S=rmfield(S,0 name0 ) Remove component: Removes the specified component, if it is the last
component, the result is an empty struct.
fieldnames(S) List of components: Returns a one dimensional cell of strings containing all com-
ponent names. The datatype cell is explained in Section 5.3.
5.3 Cells
Cells can have several dimensions of independent length. Each cell element has a variable as
content, this variable can have any datatype, matrix, string, struct and cell. The cells elements
can differ in datatype and size.
CHAPTER 5. OTHER DATA TYPES 29
>> A = {1, [2, 3], 4, [5, 6; 7, 8],’hello’}
>> A{2}
>> A{5}
>> A(5)
>> A{4}(2, 1)
>> B = {1, [2, 3]; 4,0 hello0 }
>>
{. . .} Create cells: This is one way to define cells, simply listing all the variables and data in
curly brackets. Two cells in a row are separated by a comma, rows of cells are separated
by semicolon as we are used from matrices. Keep in mind all rows need to have the same
number of cells.
A draw back of this way of defining cells is, that we can only construct one and two dimen-
sional cells.
cell(. . . ) Create cells: ”cell([3,4,2])” defines a three dimensional cell and set the element values
as empty.
A{. . .} Assessing a cell: Matlab distincts between the cell element and its contents. Using the
curly brackets we can assess the cell contents. As the cell contents is a variable, we can do
math manipulations or string operations if the datatype of the contents is matrix or string
respectively.
A(. . .) Assessing cell element: In contrast to the previous way of assessing a cell A(1) is still a
cell, so for example, we can not apply any math operation to A(1).
5.4 Sets
The datatype cell can be used for set operations, therefore the cell needs to consist of elements with
datatype string only. Further each content is only allowed to appear once, which can be achieved
using the command ”unique”.
Let A and B be sets then the following operations are defined
maths expression Matlab command
A∪B union(A, B)
A∩B intersect(A, B)
A\B setdif f (A, B)
(A ∪ B)\(A ∩ B) setxor(A, B)
Additionally there is the query function ”ismember(a,A)” which evaluates if a is a member of
A and returns the value 1 (true) if so otherwise the value 0 (false).
CHAPTER 5. OTHER DATA TYPES 30
>> A = {0 10 ,0 20 ,0 30 ,0 40 ,0 50 ,0 a0 ,0 b0 ,0 c0 ,0 d0 }
>> B = {0 10 ,0 A0 ,0 20 ,0 40 ,0 40 ,0 40 ,0 50 }
>> B = unique(B)
>> B = union(B,0 70 )
>> D = union(intersect(A, B), {0 90 ,0 70 ,0 A0 ,0 B 0 })
>> if ismember(0 30 ,D)
fprintf(0 We have lost\n0 );
end
>>
input Interactive statement: This command causes Matlab to wait until the user presses return
and provides as a result what ever the user has entered. An empty input is interpreted as a
0 × 0 matrix.
fprintf formated printing: This function is almost identical to its counterparts in other program-
ming languages. The syntax is given by
fprintf(format,parameters)
or
fprintf(file,format,parameters).
The latter we discuss again in Section 6, however, it has the same functionality as the first
just with the difference that it prints to an already opened file.
format is enclosed by single quotes and any plain text contained in format is printed as such.
However format might include formating information such as
\t tabulator
\n linebreak
Further format can contain several place holders for writing some data in this places
%d integer
%f float
%e float in exponential form
%s string
For each placeholder there should be a Parameter containing variables precisely of this format.
Often one likes to improve the printout by allowing only specific amount of places for each sort
of data,
>> fprintf(0 %f %e\n’,-pi,-pi);
>> fprintf(0 %8.4f %8.4e\n’,-pi,-pi);
CHAPTER 5. OTHER DATA TYPES 31
>> fprintf(0 %2.1f %2.1e\n’,-pi,-pi);
0
>> fprintf( %+2.1f %2.1E\n’,-pi,-pi);
>>
sprintf formated string: In principle this command works the same way as fprintf but it returns
a string, so the result can be passed on to a variable.
5.7 Exercises
Aufgabe 5.1 Enter the sets A = {a, b, c}, B = {b, c, d} and C = {c, d} and construct the sets
{a}, {} and {b, d} using set operations applied to the set A, B and C.
CHAPTER 5. OTHER DATA TYPES 32
Aufgabe 5.2 Write a function ”Forecast(Weather)”, which works on the data Weather which is
a vector of structs. Each struct has the components Place (string), temperature (number) and rain
(number). The function shall print to the screen the weather information for each vector element
in a nicely formated way.
Define W eather with the following data
place temperature rain in ml
Koeln 20 0
Duesseldorf 19 3
Frankfurt 25 0
Offenbach 17 10
Mainz 21 1
Hanau 21 0
Attention:
Matlab is a nice toolbox to work with even in case of large sets
of data. Especially it is straight forward to create huge amounts
of data, storing them will eventually if not immediately fill your
disc.
instead, so here saving the variables a, b and C. Another way to call save is to use
>> save(name,0 a0 ,0 b0 ,0 C0 )
>>
where name is now a string variable. This is useful when writing to an apriory unknown file.
Matlab extends the name of the file automatically by ”.dat”.
The opposite action of ”save” is ”load”. With
>> load name
>>
33
CHAPTER 6. EXPORTING AND IMPORTING DATA 34
>> B.content2,3 = A;
>> B.content6 = ’never no ’;
>> save set1
>> save setB B
>> clear
>> who
>> load setB
>> who
>> load set1
>> who
>>
in the file Ex input.m and execute afterwards the following on the command line
>> clear
>> Bsp input
Enter a number 4
Enter a number ’hallo’
hallo
hallo
hallo
hallo
>>
The file pores 1.mtx, downloadable from the course web site, is written in the Matrix market 1
format.
In cases where we do not know the format apriory it can be useful to read in the text as a hole
and then work through it step by step.
1 http://math.nist.gov/MatrixMarket
CHAPTER 6. EXPORTING AND IMPORTING DATA 36
>> fid = fopen(’Daten3’,’r’);
>> A = str2num(scanf(fid,’%c’));
>> fclose(fid);
>> who
>> A
>> clear
>> fid=fopen(’pores 1.mtx’,’r’);
>> text = fscanf(fid,’%c’);
>> fclose(fid);
>> R = text;
>> while (length(R))
[T,R] = strtok(R,’%’);
end
>> t = str2num(T);
>> A = spconvert(t(2:end,:));
>> full(A)
>>
Here the number 3 in rows one and two indicates that there are three data columns. In case
a different number of data columns shall be tabled then this must be altered accordingly. The
following code provides a simple solution to the problem
1 function [ ] = latextab(fn,data)
2 fid = fopen(fn,’w+’);
3 if (fid<3)
4 fprintf(’ Could not open the file\n’);
5 return;
6 end;
7 [rows,columns] = size(data.tab);
8 fprintf(fid,0 \\begin {tabular}{| l| ∗ {%d}{c|}\\\\ \\hline \n’,column);
9 for i = 1:columns
10 fprintf(fid,’& %s\n’,data.col title(i));
11 end;
12 fprintf(fid,’\n’);
13 for i = 1:rows
14 fprintf(fid,’%s ’,data.row title(i));
15 for j = 1:columns
16 fprintf(fid,’& %d ’,data.content(i,j));
17 end;
18 fprintf(fid,’\\\\ \\hline \n’);
19 end;
20
6.5 Exercises
Aufgabe 6.1 As importing data and analysing them is often an integral part of work, make sure
you understand the commands and ideas being used in this chapter.
Aufgabe 6.2 Load the file pores 1.mtx using the command ”load” and using the ”fid=fopen ...”
sequence of commands as in above script. What is the difference between text and pores 1?
Aufgabe 6.3 Implement the function latextab and insert comments, specially for the interface
description. These comments shall be accessible be ”help”.
Further create the correct input data in order to get the output for the example table.
Aufgabe 6.4 Write a function ”split”, which reads in a file, splits the text into several lines
according to some delimeters provided by the user and finally the function shall save the data in
another file. Non of the delimeters (except newline) shall be present in the outfile. The function
shall have the interface
>> split(infile,delimeter,outfile)
>>
. The variables infile and outfile are strings containing the name of the corresponding files. de-
limeter is a cell with elements of type string.
As an example for the infile one can use file ”tobesplitted” together with the delimeters ”{’hi’,’we’,’proud’,char(10)}”.
Aufgabe 6.5 Write a function ”ignore(infile)” which reads in the infile, however the infile might
have comment lines which shall be ignored. The commend lines start with ”%” sign in the first col-
umn. All other lines have the form fieldname content
CHAPTER 6. EXPORTING AND IMPORTING DATA 38
The function shall return a struct having the fieldnames as specified by the file with the matching
content.
Test your function on the file tobeignored. (Clues: strcmp, str2num and strtok are helpful.
What is the number which corresponds to the char representing a line break on your machine?)
Chapter 7
Graphic
As the graphic tools are one of the key features of Matlab there are a variety of commands dealing
with figures, hence we can present only a few of them here.
Matlab has several types of graphics available, for example for simple plots in two and three
dimensions, which have all their own command, ”plot” and ”plot3” respectively. Many of these
commands act in a similar way, which we will illustrate using the ”plot” command in Section 7.2.
7.1 Overview
Here we provide a short and incomplete overview of graphical commands.
Additionally there are plenty of commands to change the handling of the graphs or their
windows.
figure Activating a graphical window: Windows for graphical outputs are called figure plus a
positive integer. Calling ”figure(number)” then the corresponding window is activated and
in case it did not exist before it is opened. All graphical commands act on the currently
activated graphical window.
print Printing to file: With ”print -style name” the content of the currently activated graphical
window is printed to the file name. The format which is used for the graphical output can
be chosen with style. Here are several useful options possible, for example dps for ps-files,
dpsc for coloured ps-files, deps and depsc for eps-files and djpeg for jpeg files.
The filename is automatically extended by the correct file extension according to the format
specified by style.
hold Freezing of plots: Standardly any plot command deletes all old plots in the currently activated
graphical window and then plots the new graph. In order to get several plots into one
coordinate system, the graph is frozen using the command ”hold on” and all following plot
commands add their graphs to the same coordinate system. To reverse the freezing type
”hold off” or ”clf”.
39
CHAPTER 7. GRAPHIC 40
clf Clear figure: Clears the plots from the currently active graphical window, sets hold to hold off
and removes all items, such as texts, labels, lines, etc from the window if they have been set
using Matlab commands instead of graphic menu buttons.
axis Coordinate axis: Standardly Matlab sets automatically the coordinate axis. However this
can be changed by the user with the command ”axis”. The scaling of the axis are then
updated automatically.
legend Legend maker: In case there is more than one graph in a coordinate system it is wise to
label them. This can be achieved with ”legend(name1,name2,. . . ,namek)” which provides
standardly in the top right corner a small box containing the colours used and writing the
names in corresponding order next to the colours.
In order to move the box to another corner use ”legend(name1,name2,. . . ,namek,number)”
where number specifies the wanted corner.
title Writes a title: The command ”title(text)” writes the string text above the coordinate system.
xlabel Legend of the x-achis: Writes a label next to the x-achis.
ylabel Legend of the y-achis: Writes a label next to the y-achis.
In general data might be a number, a vector or a matrix. In case data is a vector one graph is
ploted, the entries of the vector data against their indices. If data is a matrix with n columns, then
n graphs are plotted within one coordinate system.
The command ”plot(data)” takes two consecutive elements from the vector data and draws a
straight line between the two points represented by the two values and their indices.
So when plotting a function in Matlab we actually do not plot this function but we connect
a set of values which lie on the exact graph. This leads to the fact that Matlab graphs do not
always represent the plotted functions accurately.
>> x = [-5:1:5]
>> f = @(x) 1./(x-0.5)
>> plot(f(x))
>>
While the function has a pole at x = 0.5 the plot does not even indicate this.
The first two results are in principle the same usage, here we only demonstrate that the orientation
of the matrices x and y does matter. In contrast the second argument differs in the third plot. We
can ask plot to use a specific colour and line style to do the plotting. The colours are
blue b red r
yellow y green g
magenta m black k
The line styles are
straight line - dotted line :
dashed line -- dash dotted line -.
and instead of lines we can get just plot at the data points
stars * dots .
circles o crosses x
squares s diamonds d
For further possibilities see ”help plot”.
CHAPTER 7. GRAPHIC 42
7.3 Movies
For presentations one occasionally likes to show a short movie. If the movie shall present mathe-
matical results we can easily construct this with Matlab.
Sometimes it is just enough to run a script but to stop at certain steps for some specified time
or until the user allows to progress. Both can be achieved using ”pause” and ”pause(time)”.
>> x = [-10:0.1:10];
>> y = [-10:0.1:10];
0 0 0
>> z = sin(y -1). b2*x. b2+y . b2*cos(x-3). b2-sin(y *x);
>> surf(x,y,z);
>> for i=0:50
view([cos(i/25),sin(i/20),0.3]);
pause(0.3)
end
>> fprintf(0 Could you spot the minimal point? \n0 );
>>
However, to construct a proper movie or better a slide show we have the following commands.
movie Runs a movie or slide show ”movie(slides,repeat,speed)” shows a sequence of frames stored
in slides. The speed is measured in frames per second. Now if repeat is a scalar, then it
represents how often the movie shall be repeated. In case repeat is a vector, the first entry
of repeat has the same meaning as in the scalar case. The remaining vectors are interpreted
as indices to the frames, so the film can be played in any order independent of the ordering
of slides.
getframe graphic to frame conversion: In order to construct a frame one has to plot and label
the graph before it is stored as a frame. movie will show this frame exactly as it has been
constructed before calling getframe. The function returns a handle to the frame.
7.4 Images
Another example for the many possibilities within Matlab:
>> load gatlin; image(X); colormap(map); axis off;
>>
image Pixel map: Given a matrix A then ”image(A)” is interpreted as a pixel graph, so the entries
in A are interpreted as indices to the current colour map.
colormap Changes the current colour map: Colormap needs a n × 3 matrix defining the colour-
coding accordingly to the rgb (read-green-blue) scheme.
>> clear;
>> clf;
>> X = rand(20);
>> image(X*60);
>> figure(2)
>> image(floor(X*3)*20);
>>
CHAPTER 7. GRAPHIC 43
7.5 Exercises
Aufgabe 7.1 Assume the one dimensional data A = [1, 4, 7, 1, 12];. Tryout the commands ”stem”,
”bar”, ”stairs” and ”pie”.
Aufgabe 7.2 How does the surface of exp(cos(x)) ∗ sin(y) look like for x, y ∈ [0, 10]. Add labels
and a title to the graph.
Aufgabe 7.3 The island Neverland recently had an election and the following table provides the
results.
first try 244
the winner is 2074
best result ever 488
always second 1586
no chance 110
one vote 1
Your task is now to provide graphs for this set of result illustrating the outcome of the election.
First you should show in a stab diagram how many percent each party achieved. Then the people
like to know how many seats each party got, but attention this island has a 5 % limit, saying parties
who got less than 5% will not get any of the 72 seats. Please make use of the ”text” command in
order to label your plots.
Chapter 8
Like the graphic commands the methods for solving numerical linear algebra problems is a key
part of Matlab. As there are too many such routines we only discuss a few here.
”gallery” provides about 40 different special matrices, like Wilkinson famous matrices.
44
CHAPTER 8. NUMERICAL LINEAR ALGEBRA TOOLS 45
With ”diag”, ”tril” and ”triu” one can construct iterative methods for solving linear systems.
Methods such as the Jacobi iteration or the Gauss-Seidel iteration are easily constructed using
these tools.
>> b = rand(5,1);
>> D = diag(diag(A));
>> L = tril(A);
>> U = triu(A);
>> x = b;
>> y = A\b; % exact solution for comparison
>> for i = 1:10
x = D\((D-A)*x+b);
fprintf(’error ||x − y||=%f \n’,norm(x-y));
end;
>>
In order to obtain a full matrix from a sparse we can use the command ”full”.
>> A = spdiags(ones(100,1)*[-1,-1,5,-1,-1],[-20,-1,0,1,20],100,100);
>> B = full(A);
>> C = sparse(B);
>> D = A-C;
>> whos
>> spy(C);
>>
The upper list is extremely short. (This is not even the tip of the iceberg.) For a better overview
on Krylov methods for solving linear systems see the book by Youcef Saad, ”Iterative Methods for
Sparse Linear Systems”. However, besides Krylov methods there are many other iterative schemes
for solving linear systems.
In many situations iterative methods on their own do not work sufficiently well and require some
sort of preconditioning. The Matlab commands ”luinc” and ”cholinc” construct some popular
preconditioners.
8.3 Exercises
Aufgabe 8.1 Define a 200 × 200 Matrix A which has the value 2 along its main diagonal and the
first upper and lower diagonal entries equal to −1. How much memory does this matrix require
in sparse and in full format. (The command ”whos” provides memory information of the current
variables.)
CHAPTER 8. NUMERICAL LINEAR ALGEBRA TOOLS 48
Aufgabe 8.2 Consider the matrix from Exercise 8.1. Calculate the Cholesky decomposition of this
matrix? Can the Cholesky factor be stored in a more efficient way? Is it possible to construct the
Cholesky decomposition using ”cholinc”? What happens if you calculate the Cholesky decomposition
of the same matrix but now of size 100000 × 100000?
AT Ax = AT b (8.2)
has the same solution as the least square problem, however a better way to calculate the solution is
to construct the lean qr decomposition ”[Q,R] = qr(A,0)” and then solve
Rx = QT b. (8.3)
Download leastsquare1.m and call ”leastsquare1” to construct the matrix A and the vector b.
Calculate the solution of above problem a) by solving (8.2) and b) by solving (8.3). Is there any
difference in the solution?
Chapter 9
Numerical Methods
In contrast to the methods from Numerical Linear Algebra many numerical methods are not part
of the core routines. There exist a variety of toolboxes which we do not consider here, which
provide able tools for specific tasks.
However, of the tools already available within the Matlab core we only discuss a selection
here.
9.1 Polynomials
The simplest class of functions are polynomials, for which Matlab provides some special tools.
poly Conversion of roots to coefficients: For a vector of (complex valued) roots a normalised
polynomial is defined where the first entry corresponds to the highest order of the polynomial
and its entry is set to one. The length of the returned vector is one more than the degree of
the polynomial.
polyval Evaluation of polynomials: ”polyval(p,x)” returns p(y) for all entries y within x. Here p
needs to be the coefficient vector such that the polynomial has the form
n
X
zij = pk (xij )k .
k=0
roots Roots of a polynomial: This is the inverse function to ”poly” as it calculates the roots of the
polynomial. While ”roots” is the inverse of ”poly”, ”poly” is not the inverse of ”roots”!
polyvalm Evaluation of a matrix polynomial: As the function ”polyval” works entry wise it is not
a matrix operation in the mathematical sense. ”polyvalm” uses the matrix multiplication and
thereby provides the correct result.
polyfit Approximation with polynomials: For a given set of data points, ”polyfit(X,Y,N)” returns
the coefficients of the least square polynomial fitting problem with degree not exceeding N .
spline Piecewise approximation: Also a polynomial fitting technique, but instead of one polyno-
mial matching at all data points, this technique finds a set of polynomials. ”spline(X,Y)”
returns the coefficients of piecewise cubic polynomials which interpolate the data and satisfy
some smoothness properties.
(In fact the result has the datatype piecewise polynomial, however the result is a struct, with
the entry form = ’pp’.)
”spline(X,Y,points)” does not return the coefficients but returns the y-values for the splines
evaluated at points.
49
CHAPTER 9. NUMERICAL METHODS 50
ppval Evaluation of piecewise polynomials: This function evaluates the piecewise polynomial re-
turned by ”spline”.
conv Convolution: ”conv(a,b)” returns the polynomial which is generated by multiplying the
polynomials a and b.
>> % An example: (x)= (x-1). b4
>> a = [1,-4,6,-4,1];
>> z = [-1:0.1:2];
>> plot(z,polyval(a,z));
>> b = roots(a)
>> c = poly(b)
>> error = c - a
>>
As the above problem shows, the calculation of roots of polynomials can be poorly conditioned.
>> % Approximation of sqrt(x)+sin(x) in the interval (1,20)
>> x = [1:20];
>> y = sqrt(x) + sin(x);
>> z = [0:0.1:21];
>> figure(1); clf;
>> plot(z,sqrt(z)+sin(z)); hold on
0 0
>> plot(x,y, ∗ );
>> p1 = polyfit(x,y,2);
>> p2 = polyfit(x,y,4);
>> p3 = polyfit(x,y,6);
>> [p4,S,m] = polyfit(x,y,10);
>> plot(z,polyval(p1,z),’y’);
>> plot(z,polyval(p2,z),’m’);
>> plot(z,polyval(p3,z),’r’);
>> plot(z,polyval(p4,(z-m(1))/m(2)),’k’);
>>
Above problem is badly conditioned and when increasing the approximation degree, then it
even fails. In order to improve the conditioning one can use three return variables for ”polyfit”, as
done for the last example. For more please refer to ”help polyfit”.
9.2 Quadrature
The evaluation of a specific integral is known as quadrature. While Matlab offers several function,
we restrict here to the following ones.
Rb
quad adaptive Simpson: ”quad(f,a,b)” calculates the value of the integral f (x)dx using the
a
adaptive Simpson scheme. The error is for smooth function smaller than 10−6 .
quadl Adaptive Gauss-Lobatto: Similar to ”quad” however here the adaptive Gauss-Lobatto scheme
is used, which is based upon orthogonal polynomials.
dblquad Two dimensional quadrature: Works similar to ”quad” however now for two dimensional
problems.
CHAPTER 9. NUMERICAL METHODS 51
triplequad Three dimensional quadrature: Works similar to ”quad” however now for three dimen-
sional problems.
>> f = @(x) exp(-sqrt(x)).*sin(x);
>> quad(f,0,10)
>>
Note, that the multiplication is pointwise, otherwise the quadrature commands will fail!
9.3 Probability
rand Equally distributed random variables: ”rand(n)” returns a n × m matrix with entries equally
distributed in [0, 1].
randn Gaussian distributed random variables: Like ”rand”, but now a Gaussian / normal distri-
bution has been applied.
mean Mean value: Given a vector it calculates its mean, given a matrix it calculates the column
means.
std Standard deviation: Similar to ”mean” but now the standard deviation.
var Variance: Like ”mean” but now for the variance.
cov Covariance: The entry must be a matrix and its columns represent different experiments
while its row represent the realizations of different random variables.
median Median: Like ”mean” but now for the median.
The classical problem of Fourier transformation is also solvable within Matlab which is quite
handy for many applications.
fft Fast Fourier transformation: ”fft(a)” returns the Fourier transformed values of the vector a.
Further when calling ”fft(a,n)” the result is the Fourier transformed of b, where b = a(1 : n)
if n < length(A) and b = [a; zeros(n − length(a), 1)] otherwise.
ifft Inverse fast Fourier transformation inverse of ”fft”.
The fast Fourier transformation is applied when calculating the convolution of two polynomials,
>> a = [2,3,1,6];
>> b = [7,1,3];
>> c = conv(a,b)
>> af = fft(a,8)
>> bf = fft(b,8)
CHAPTER 9. NUMERICAL METHODS 52
>> df = af.*bf
>> d = ifft(df )
>> d = d(find(d))
>>
A numerical approximation (ignoring the exact solution) can be calculated using for example
”ode45”.
>> f = @(t,x) [-0.1,1;-1,-0.1]*x;
>> interval = [0,10];
>> start = [1;0];
>> tic,[T,X] = ode45(f,interval,start);toc
>> plot(T,X);
>> % As comparison
>> hold on;
0 0
>> plot(T,exp(-T/10).*cos(T), r );
>>
A good guide to these tools is the book by Higham & Higham ”Matlab guide”.
Another standard problem with ODEs are boundary value problems such as
This problem describes a drop of water. One possibility to solve such problems is to use shooting
methods which reduce this problem to a sequence of initial value problems to be solved. Another
approach is to use collocation, which are more robust but usually not that accurate.
bvp4c Boundary value problem solver: ”bvp4c” is a fast and easy to use boundary value solver
based on collocation.
CHAPTER 9. NUMERICAL METHODS 53
∂u ∂2u
= ∀t ∈ [t0 , T ], ∀x ∈ Ω.
∂t ∂x2
Depending on the form of the PDE, various conditions for the boundaries have to be specified.
Matlab provides one reasonable solver for some advection diffusion type PDEs in one space
dimension, ”pdepe”.
Consider a PDE of the form
∂u ∂
c(x, t, u, ux ) = x−m (xm f (x, t, u, ux)) + d(x, t, u, ux )
∂t ∂x
where m = 0, 1 or 2. Here c, d and f are functions depending on space x, time t, current value of
the unknown u and its spatial derivative ux . In order to work with ”pdepe” we need a function F
with
c(x, t, u, ux )
F (x, t, u, ux ) −→ f (x, t, u, ux ) .
d(x, t, u, ux )
Similar to the odes we need some initial conditions, that are the values of u at t = 0, these values
should be provided by a function, say initial, with values = initial(points). Additionally we need
boundary conditions of the form
for the right boundary x = b. These conditions need to be supplied as a function, say bound, of
the form
pa
qa
bound(xa, ua, xb, ub, t) −→
pb ,
qb
Note that F and bound need to be defined within M − f iles as their output need to have three
or respectively four components.
Further we need to define a grid and a time span, tspan for which the problem is to be solved.
Both grid and tspan need at least three entries and all the entries must be in increasing order.
While tspan has little or no influence on the time integration the variable grid has. Only at the
points specified in grid, the calculation is carried out! (More points leads to more work and higher
accuracy.)
Finally we can call the Matlab solver for PDEs with ”pdepe(m,F,initial,bound,grid,tspan,options)”
where options is an optional struct specifying some tuning parameters.
9.7 Exercises
Aufgabe 9.1 Make sure you understand all the examples, best you test them carefully and make
use of the ”help” command.
CHAPTER 9. NUMERICAL METHODS 54
Aufgabe 9.2 Given the polynomials p(x) = (x−3)(x−2)(2x2 +2x+1) and q(x) = (x+1)(x3 +x).
Calculate the coefficients of p, q and of p · q. What are the zeros of p, q and p · q?
Aufgabe 9.3 Consider the ordinary differential equation (9.1). Let ”A=[-0.1,1;-1,-0.1]” then the
solution can be written as u(t) = @(t, x0)exp(A ∗ t) ∗ u0 (”u = expm(A*t) * u” in Matlab). Using
the Jordan decomposition, see ”[V,D]=eig(A)”, we can write this as u(t) = @(t, x0)V ∗ exp(D ∗ t) ∗
V −1 ∗ u0 (now there is no difference between exp and expm). Further we can use any of the ode
solvers and we know the exact solution. Approximate the solution by different means and compare
the quality of them. How much time does the calculation take?
(In order to determine the timing you can use ”tic” and ”toc”.)
Aufgabe 9.4 Calculate a solution for the heat equation on the unit interval, Ω = [0, 1] with initial
values according to u0 (x) = 1/(0.1 + (x − 0.5)2) and boundary condition ux (t, 0) = 0 at the left and
u(t, 1) − 10ux(t, 1) = 0 at the right end. Plot the results for times [0 : 0.1 : 1].
Chapter 10
Examples
55
CHAPTER 10. EXAMPLES 56
21 X = round(M/3+1);
22 else
23 X = congX;
24 end
25 else
26 X = S;
27 end
28 Y = zeros(n,1);
29 for i = 1:n
30 X = mod(a*X+b,M);
31 Y(i) = X/M;
32 end
33 congX = X;
34
Usually variables of a function just exist within the function, unless they have been defined as
global using the command ”global”. This is done here to save the state variable of the pseudo
number generator so that a second call of the pseudo number generator does not return the same
values. If we use the variable first before we define it as global this will create an error, because the
same variable might be already known outside the function and thus two variables would clash. As
the command ”global ” already defines the variable either having the content of an outside variable
with the same name or with no content, so being empty. Thus the variable exists but might be
empty and hence our check on line 19.
Another class of random number generators are the Fibonacci methods which use
a = U i − Uj
if a < 0, set a = a + 1
Ui = X = a
reduce i and j by 1
if i = 0 or j = 0, set i = k respectively j = k
Some of these methods are already known for many years however in the last 15 years they have
been improved massively and are now the best around.
1 % A simple Fibonacci random number generator
2%
3 % Y = Fibonacci(N,U)
4 % returns N equally distributed random numbers in the
5 % interval (0,1). When calling Fibonacci the first time and
6 % U is not specified then the internal state U is chosen as
7 % U = [7,18,21,4,9,29,sqrt(2),sqrt(5),3,2,17]/31.
8 % Whenever U is specified it is taken as the new state.
9%
10 function Y = Fibonacci (n,U,varargin)
11 global FibonacciX FibonacciI FibonacciJ FibonacciK
12 if (nargin<1)
13 fprintf(’Not enough input variables\n’);
14 Y = -1;
15 return
16 end
17 if (nargin<2)
18 if isempty(FibonacciX)
CHAPTER 10. EXAMPLES 57
19 X = [7,18,21,4,9.29,sqrt(2),sqrt(5),3,2,17]/31;
20 I = 3;
21 J = 8;
22 K = 11;
23 else
24 X = FibonacciX;
25 I = FibonacciI;
26 J = FibonacciJ;
27 K = FibonacciK;
28 end
29 else
30 X = U;
31 K = length(U); I = round(K/3); J = round(4/5*K);
32 end
33 Y = zeros(n,1);
34 for i = 1:n
35 y = X(I)-X(J);
36 if (y<0)
37 y = y+1;
38 end
39 Y(i) = y;
40 X(I) = y;
41 I = I-1; J = J-1;
42 if (I==0)
43 I = K;
44 end
45 if (J==0)
46 J = K;
47 end
48 end
49 FibonacciX = X;
50 FibonacciI = I;
51 FibonacciJ = J;
52 FibonacciK = K;
53
In order to test the random number generators here are some numbers they should live up to.
1 1
mean 2 variance 12
skewness 0 kurtosis 1.8
1
median 2
The following function uses a specified random number generator and calculates above variables
and provides a little graphic illustrating the quality.
1 % Test tool for random number generators
2%
3 % out= GenTest(Generator,N,K);
4 % Generator needs to be a random number generator.
5 % N is the number of random variables to be chosen and
CHAPTER 10. EXAMPLES 58
6 % K is used for the correlation test, checking if there
7 % is a correlation between K consecutive numbers.
8 %
9 % out is a struct containing the interesting values
10 %
11 function out = GenTest(Gen,n,k)
12 X = Gen(n);
13 MX = mean(X);
14 Z = X-MX;
15 out.mean = MX;
16 out.variance = var(X);
17 out.kurtosis = mean( Z. b3 );
18 M2 = mean( Z. b2);
19 M4 = mean( Z. b4);
20 out.kurtosis = M4/M2 b2;
21 out.median = median(X);
22 %%%%
23 % Now we start with the correlation analysis
24 %%%%
25 d = [1:n-k]’;
26 ind = d ∗ ones(1, k) + ones(n − k, 1) ∗ d(1 : k)0 − ones(n − k, k);
27 Y = X(ind);
28 C = cov(Y);
29 out.corr = norm(C – eye(k));
30 fiugre(1); clf;
31 if (n < 101)
32 plot(Y(:,1),Y(:,2),0 .0 );
33 else
34 scatter(Y(:,1),Y(:,2),1);
35 end
36