You are on page 1of 59

An introduction to Matlab

J. Berns-Müller

September 26, 2006


Contents

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

2 Numbers and Matrices 8


2.1 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2 Definitions of numbers, vectors and matrices . . . . . . . . . . . . . . . . . . . . . . 8
2.2.1 numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2.2 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2.3 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3 Working with matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.3.1 Matrix versus vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.4 Matrix Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.4.1 Unitary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.4.2 Binary Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.5 Matrices, Functions and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.5.1 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.5.2 Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.5.3 Some standard functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.5.4 Further Matrix Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

3 Script and Function Files 16


3.1 General . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2 Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.3 A first script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.4 Template for script files – hand in homework . . . . . . . . . . . . . . . . . . . . . 17
3.5 A first function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.6 Inline-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.6.1 Subfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.7 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

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

5 Other data types 27


5.1 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
5.2 Structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.3 Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
5.4 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
5.5 Working with strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
5.6 Working with blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

6 Exporting and Importing Data 33


6.1 Saving and reading of Matlab data . . . . . . . . . . . . . . . . . . . . . . . . . . 33
6.2 Export and Import of ASCII Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.2.1 Writing ASCII data to a file . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.2.2 Reading from keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.2.3 Reading from a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.3 Importing and Exporting Data from/to Databases . . . . . . . . . . . . . . . . . . 36
6.4 A detailed example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
6.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

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

8 Numerical linear algebra tools 44


8.1 Full matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
8.1.1 Defining matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
8.1.2 Calculating with matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
8.1.3 Matrix decompositions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
8.2 Sparse matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
8.2.1 Constructing sparse matrices . . . . . . . . . . . . . . . . . . . . . . . . . . 46
8.2.2 Iterative methods for linear systems . . . . . . . . . . . . . . . . . . . . . . 47
8.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

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

1.1 General Remarks


This script is part of the introductory course on ”Programming with Matlab”.

1.1.1 What is Matlab


Matlab is a commercial product, originally developed by Cleve Moler. Today Matlab is one of
the most widespread mathematical programming platforms. Here we just consider the basic part
of Matlab, however there are many additional toolboxes available.
All toolboxes as well as the basic part are available via
The MathWorks Inc.
3 Apple Hill Drive, Natick, MA 01760-2098
http://www.mathworks.com
or their German distribution center
The MathWorks GmbH:
Friedlandstraße 18
D-52064 Aachen
Phone: 024147075-0
Fax: 024147075-12
In case you are interested in student licenses please check the following web page:
http://www.mathworks.de/academia/student center/

1.1.2 Why might Matlab be useful


• In industry Matlab is a standard tool for solving mathematical problems numerically.
• Mathematical codes might be written in C or Fortran. Nevertheless, mathematical software
development is largely done using Matlab.
• There are several toolboxes around to solve advanced and complicated problems.
• The linkage of Matlab and Simulink (also from MathWorks) provides engineers with math-
ematical tools and engineering blocks, to easier develop sophisticated machines etc.

These developments are based on some advantages


• automatic memory allocation
• automatic data type conversion

4
CHAPTER 1. INTRODUCTION 5

• precise error messages


• high quality math routines

• freely available source codes for many functions


• large variety of easy to use graphic tools
• memory efficient data representations and routines which exploit sparsity
There are many other mathematical software packages which are brilliant for their special
applications. Many of them are specialized for a specific area of mathematics. Matlab is no
exception, it is not designed to do analytical or axiomatic calculations. Matlab was originally
designed for Numerical Linear Algebra and its Applications and has grown now into Numerical
programming and its Applications.
The following lest of mathematical packages and libraries is not exhaustive and for example
many more numerical libraries can be found on ”www.netlib.org”.
maple Computer Algebra System, specially for Functional Analysis
gap Computer Algebra System for experts, specially in Algebra

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)

1.2 First Steps


From the Unix/Linux command line one can start Matlab simply by typing matlab to get the
development center or matlab -nojvm to get the Matlab shell. Matlab can be started from
any directory, actually it makes sense to create several directories and subdirectories to work with
Matlab, as one creates various files containing data or Matlab-functions.
Starting the Matlab development center one usually gets several windows, one of which is the
command window. This command window and the Matlab editor will be the main tools, the
remaining windows can be deleted without any worry. In case we need one of these windows we
can get them easily from the pull down menu ”windows”.
In the command window you will find the Matlab prompt

>>

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)

Starting, but generally more advanced:


CHAPTER 1. INTRODUCTION 7

Desmond Higham & Nicholas Higham Matlab guide (SIAM)


Darren Redfern & Colin Campbell The Matlab Handbook (Springer)

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

Aufgabe 1.3 Please try the following sequence of commands




>> clear

>> area= pi*r

>> r=2;

>> area=pi*r b2

>> area

>> area = @(r) pi*r b2

>> area(2)

>> area(3)

>>

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 exact solution of this problem is the cosine-function.


The following code forces Matlab to provide a numerical solution to our initial value problem
and plots the solution.


>> f=@(t,x) [0,1;-1,0]*x;

>> [t,x] = ode45(f,[0:0.1:10],[1;0]);

>> plot(t,x(:,1))

>> plot(t,x(:,1)-cos(t))

>>

(The last line plots the error between the numerical approximation and the exact solution.)
Chapter 2

Numbers and Matrices

2.1 Basics
The basic datatypes in Matlab are

matrix, string, cell, struct.

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

2.2 Definitions of numbers, vectors and matrices


2.2.1 numbers
Lets start with two simple lines


>> a = 1;

>> a

>>

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.

Some more variants to define the same matrix




>> clear

>> A=[[1,2;4,5],[3;6];...

[7;10],[8,9;11,12]];

>> A=[[1;4;7;10],[2;5;8;11],[3;6;9;12]];

>> clear

>> A=[];

>> A=[A;1,2,3];

>> A=[A;4,5,6];

>> A=[A;7,8,9];

>> A=[A;10,11,12];

>> clear

>> A(1,1)=1;

>> A(1,2)=2;

>> A(1,3)=3;

>> A(2,1)=4;

>> A(2,2)=5;

>> A(2,3)=6;

>> A(3,1)=7;

>> A(3,2)=8;

>> A(3,3)=9;

>> A(4,1)=10;

>> A(4,2)=11;

>> A(4,3)=12;

>>

The command ”A= [ ]” defines an empty matrix. An empty matrix is of size 0 × 0.




>> size(A)

>> size([ ])

>>
CHAPTER 2. NUMBERS AND MATRICES 11

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

>>

: Colon: The colon operator, a : b, is an efficient way to get the numbers a, a + 1, a + 2, . . . , a + k,


with k being the largest integer such that a + k is smaller equal to b. If a and b are positive
integers, than a : b is an integer valued vector, which can be used as an index vector.
The command ”a:b:c” provides the numbers a, a + b, a + 2b, a + 3b, . . . , a + kb with k being
the largest integer not larger than (c − a)/b. Matlab allows B to be negative.

2.3 Working with matrices


We can easily access a single entry of a matrix my calling


>> a=A(2,3);

>>

An entire vector and a submatrix can be accessed in similar fashion




>> b = A(:,2);

>> b = A(1:3,2);

>> B = A(1:3,2:3);

>>

2.3.1 Matrix versus vector


As the computer memory is accessed as a one dimensional array Matlab provides us to access
matrix entries by a single index.


>> A = zeros(3,4);

>> [1:12]

>> A(:) = [1:12]

>> A(5:9)

>>

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.

2.4 Matrix Operation


Here we distinct (a bit artificially) between unitary and binary operators. Unitary operators act
only on one matrix, while binary operators connect two matrices in a mathematical way.

2.4.1 Unitary Operations


There are three unitary operators
- Negation: ”B=−A” provides the negative of A.
.0 Transposition: ”B = A.0 ” assigns the transpose of A.
0
Transposition and complex conjugation: ”B=A0 ” assigns the transpose and complex conjugate of
A.
Examples


>> A = [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12]

>> B = A0

>> C = A.0

>> A(1, 1) = 1 + 2i

>> D = A0

>> E = A.0

>> F=−A

>>

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.4.2 Binary Operators


In case of binary operations we need to take care of the dimensions of the matrices in use. In case
of mismatch of dimensions, Matlab will post an error immediately.
First we take a look at the standard actions for matrices with matching dimensions


>> B = A + A;

>> C = A0 ∗ A;

>> D = B − A;

>> a = [1 : 4];

>> E = a0 ∗ a;

>> f = a ∗ a0 ;

>> G = C b2

>>
CHAPTER 2. NUMBERS AND MATRICES 13

Further we can multiply a matrix by a scalar and divide a matrix by a scalar




>> b=2;

>> c=b*A

>> d=A/b

>>
however b must differ from 0 for the division, otherwise the entries are inf and a warning is stated.
Matlab knows further matrix operators which interpret the matrix as an array of numbers.
In this case the action is element wise


>> B = A. b2

>> B=A./A

>> C=A.*A

>>
Further, Matlab provides the solution operators ”\” and ”/” for the linear equations Ax = b
and xA = b. Consider the linear equation Ax = b where A and b are known and x shall be
calculated


>> b = [1 : 4]0

>> c = [1 : 4];

>> A = [1, 2, 3, 4; ...

4,5,6,7;...

7,7,9,9;...

10,10,10,11];

>> x = A \ b;

>> y = c/A;

>> % This is a comment line, commends can be started anytime in a line

>> % and they run until the end of line,

>> % hence there is no end of comment required

>>

>> % Probe

>> A*x-b

>> y*A-c

>>
(When calling ”A/b” or ”b\ A” then Matlab will construct an L U decomposition of A, which are
then applied to all columns, rows respectively, of b, so b is allowed to be a matrix!!)

2.5 Matrices, Functions and Constants


Most Matlab functions can be called with numbers, vectors or matrices as arguments. We now
present a small selection of functions which can be called with matrices of any kind as argument.
However, beforehand we consider a few already defined constants.

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

2.5.2 Trigonometric Functions


Matlab uses two sets of trigonometric functions, following functions work in rand
sin cos tan cot
asin acos atan acot
sinh cosh tanh coth
asinh acosh atanh acoth
and the next ones work in 360 degrees
sind cosd tand cotd
asind acosd atand acotd
For large arguments it is sensible to work in degrees as then the numerical evaluation is more
precise, as indicated by the following example


>> sin(pi)

>> 3e12 - 3*10 b12

>> sin(e3e12*pi)

>> sind(3e12*180)

>>

2.5.3 Some standard functions


Here we present only a few standard function, more numerical functions will be discussed in
Chapters 8 and 9. The following function interpret a given matrix as an array and applies the
function element wise
exp(a) exponential function log(a) natural logarithm
log2(a) logarithm with base 2 log10(a) logarithm with base 10
real(a) real part imag(a) imaginary part
abs(a) modulus sign(a) sign function, direction

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 command ”norm(A,p)” needs to be p equal to either 1, 2, inf or 0 f ro0 .

2.5.4 Further Matrix Operation


These commands change the shape and ordering of the elements of a matrix.

f liplr column permutation f lipud row permutation


rot90 rotation of a matrix permute permutation of the coordinate system
ipermute Inverse of ”permute” reshape general change of shape

(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.2 Calculate the quotients 1 + 3i and 1 − 2i.



17−5
Aufgabe 2.3 What does e3 −5 equal?

Aufgabe 2.4 Evaluate the solution of the linear system


   
1 2 1 0 1
 2 3 2 1   1 
 x =  .
 1 2 4 2   1 
0 1 2 3 1

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

Script and Function Files

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.

3.3 A first script


Starting with a simple example for a script, we just enter the following to the editor


1 display(0 A first Script0 );

2 clear

3 who

4 A = [1, 2, 3; 4, 5, 6]

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

>>

3.4 Template for script files – hand in homework


For your electronic hand in homework we have a special Matlab script file, which you only need
to download, modify, run and mail the thereby created file to your tutor.
The script file has the following format


1 %% Script-file: assessment

2 % your comments

3 clear
CHAPTER 3. SCRIPT AND FUNCTION FILES 18


4 surname = 0 Sharp0 ;

5 firstname = 0 Bob0 ;

6 course = 0 Matlab0 ;

7 sheet = 1;

8

9 %%%%%%%%%%%%

10 % Do not change these lines

11 file=sprintf(0 %s %s %d0 ,surname,firstname,sheet);

12 delete(file);

13 diary(file);

14 fprintf(0 Name: %s, %s\n0 ,surname,firstname);

15 fprintf(0 %s %d\n0 ,course,sheet);

16 echo on;

17 %%%%%%%%%%%%

18 % Task 1

19 % Please insert here your solution as described on the how

20 % to hand-in web-page of your course

21

22 %%%%%%%%%%%%

23 % Task 2

24 % Please insert here your solution as described on the how

25 % to hand-in web-page of your course

26

27 %%%%%%%%%%%%

28 % Do not change these lines

29 echo off

30 diary off

31

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.

3.5 A first function


As a first example for a function we plot the sine function


1 % Function-file: plotsin: plot sine function

2 %

3 % plotsin(N) returns the functions values of the sine function

4 % for N+1 equal spaced X values in [0,2*pi]. Further the function

5 % plots the corresponding curve.

6 % [Y,X] = plotsin(N) returns the function values, Y, and their

7 % corresponding X values.
CHAPTER 3. SCRIPT AND FUNCTION FILES 19


8 function [y,x] = plotsin(n);

9 x = [0 : 2 ∗ pi/n : 2 ∗ pi];

10 y = sin(x);

11 plot(x,y);

12

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)

>>

where q is the inline function ”q = @(x) x. b2-3”.

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.

4.1.1 Branching with if




1 if (a>1)

2 fprintf(’a is larger than 1\ n’);

3 elseif (a>-3 & a<-1)

4 fprintf(’a is between -3 and -1\ n’);

5 else

6 fprintf(’Where is a?\ n’);

7 end

8

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

>>

For mathematical comparisons we have the operations


> larger < smaller
>= larger equal <= smaller equal
== equal ∼= not equal

4.1.2 Branching with switch


The ”switch” command allows to branch into multiple branches. For example if a variable can have
several different values (limited in number) then for each value a different branch can be selected.
However in contrast to other languages Matlab allows to group several cases as one branch.


1 switch(B)

2 case ’a’,

3 fprintf(’Variable B is of tye string and has the value %c’,B);

4 case 1,

5 fprintf(’Variable B is of tye matrix and has the value 1’);

6 case {2,3},
CHAPTER 4. CONDITIONAL STATEMENTS 24


7 fprintf(’Variable B is of tye matrix and has the value %d’,B);

8 otherwise

9 fprintf(’Variable B is defined, but we do not know any more’);

10 end

11

4.1.3 Searching with find


Often we need to check components of a matrix or vector or even just to change a few of them
according to some indicator. Matlab provides with the ”find” command a very useful tool for
this task.
find Vectorized query: ”find(condition)” returns the indices of the vector/matrix for which the
condition vector/matrix has the value true, that is a value different from zero.


>> A=[1:2:10,1:3:10,1:4:10]

>> find(A<6)

>> B=[1:10]’*[1:5]

>> k=find(B<6)

>> [i,j] = find(B<6)

>> ind2sub(size(B),k)

>>

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.

4.2.1 The fixed loop for


This type of command is useful if a fixed number of cycles of the loop need to be performed. A
first simple example for a for loop


1 f or i = 2 : 10

2 b(i) = i;

3 end;

4 c = [1 : 10]0 ;

5
The vectors b and c differ only in their first element. As Matlab first evaluates the vector for
which the loop need to be run, that is all values for i = [2 : 10], it is also possible to use negative
numbers, negative increments, and non integers for the variable i.


1 start = -3;

2 increment = 1.5;

3 stop=2*pi;

4 for i = start : increment : stop

5 fprintf(’i has now the value i = %f \n’,i);

6 end;

7
CHAPTER 4. CONDITIONAL STATEMENTS 25

4.2.2 The conditional loops while


The while command uses a boolean condition which is evaluated at the beginning of each cycle,
the loop stops if at the beginning of one cycle the condition is false, that is the condition has the
value zero.


1 i = 1;

2 while (i<9.5)

3 i = i+pi;

4 fprintf(’i has now the value i = %f \n’,i);

5 end;

6
As every value different from zero represents the boolean meaning true the following example
presents and endless loop.


1 i = 0;

2 while 1 % this makes the loop an endless one

3 i = i+pi;

4 if and(i<10*pi,i>pi)

5 fprintf(’We do nothing \n’);

6 continue

7 end;

8 fprintf(0 i has now the value i = %f \n’,i);

9 if (i>20*pi) % however here we stop the loop

10 break;

11 end;

12 end;

13

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.

Another example for loops, here an upper right matrix is defined




1 j=1;

2 while (j <= 20)

3 for i=1:j

4 A(i,j) = i b2+j b2-(i*j);

5 end
CHAPTER 4. CONDITIONAL STATEMENTS 26


6 j = j+1;

7 end

8

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

Other data types

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

string, struct and cell

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

Some more examples for cells.




>> A = [1, 2; 3, 4];

>> B = {A, A b2, A b3, A b4}

>> C = {’hello’,’world’,’What shell we say?0 }

>> D = {A, B; {}, C}

>> D(3)

>> D{3}

>> D(2)

>> D{2}

>> D{2}{2}

>>

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

>>

5.5 Working with strings


There are many functions available under Matlab to modify, read and write strings. Here we
present only a few of them, for further information please see ”help strings” and ”help strfun”.
For writing interactive codes, the commands ”input” and ”fprintf” are useful.


1 value = input(’Please enter an integer \n’);

2 fprintf(’You entered %d \n\t Thanks \n’,value);

3

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.

We have used fprintf and sprintf already in Section 3.4.


Some useful function for working with strings
strcat concatenating strings
strcmp comparing strings
strfind searching strings within strings
strtok splitting strings according to a list of token
More functions to work with strings can be found by calling ”help strings” and ”help strfun”.

0 0
>> A = hello ;

>> B = world 0 ;
0

>> C = 0 How 0 ;

>> D = 0 is 0 ;

>> E = 0 life 0 ;

>> F = 0 fine 0 ;

>> greeting = strcat(A, ’ ’,B)

>> question = strcat(C; ’ ’,D, ’ ’,E)

>> u = strfind(question,’ ’)

>> if strcmp(D,question(u(1)+1,u(2)-1))

fprintf(’%s %s %s\n’,E,D,F)

end

>>

5.6 Working with blocks


We have already seen how to create cells and how to access cell elements and their contents. Here
we provide a few more commands on working with cells.
cell(. . .) Creating cells
cellplot(B) Plots the structure of the cell, and writes the content into the plot.
celldisp(B) displays the cell content element wise to the screen. (Only in modern versions)
iscell(B) test if a variable is of type cell.
iscellstr(B) tests if all cell elements are strings. (For example when using cells as sets, then all
the cell elements need to be strings.)

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

and call ”Forecast(Weather)”.


Chapter 6

Exporting and Importing Data

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.

6.1 Saving and reading of Matlab data


For saving all Matlab data in a file, say name, we can call


>> save name

>>

To save only a collection of variables we can use




>> save name a b C

>>

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

>>

we recover the data which we stored with the ”save” command.




>> A = zeros(3,4);

>> A(:) = [1:12];

>> B = struct(’what’,’unsorted Data ’,’content’,cell(2,4));

>> B.content1 = ’hallo world ’;

>> B.content2,1 = ’ and now? ’;

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

>>

6.2 Export and Import of ASCII Data


6.2.1 Writing ASCII data to a file
The command ”save” writes the Matlab data in coded form so that these data are not easy to
import for other tools. However most tools allow the import and export of ASCII data. As ASCII
data can be viewed by most editors one can check the format of the data and then adapt the
importation of those data or simply their interpretation.
In order to read and write ASCII data we have seen already some commands but let us restate
them together with some new ones
fopen Opens and creates files: The command ”fopen(’name’,’action’)” opens the file name either
for reading or writing dependent on the specified action.
If the actions is r, then the already existing file name is opened, however if the file does not
exist no file is opened. The thus successfully opened file we can now access and read.
In case the action is w+, then the file will be opened whether or not the file exists. The file is
anyway truncated to length zero. One can assume that the file has been deleted and created
again. Now we can start writing to this file.
If fopen is successful it returns a value larger than 2. The returned number is the file identifier
and can only be used in connection with fprintf, fscanf and fclose (and similar functions).
fprintf Formated writing: The functionality has been discussed in Section 5.5, where we said the
syntax is fprintf(file,format,parameters). Here file is the file identifier returned by fopen.
fclose Saving the data: Actually no data are safely stored before calling ”fclose(file)”, where file is
again the file identifier. Additionally the file is closed and any further use of the file identifier
file will cause an error.
Our typical example matrix A can be stored as follows


>> A = zeros(3,4); A(:) = [1:12];

>> fid =fopen(’Data3’,’w+’)

>> fprintf(fid,’%%% this file contains the data of a matrix\n);

>> fprintf(fid,’% which can be read using load \n’);

>> for i = 1:3

for j = 1:4

fprintf(fid,’%e ’,A(i,j));

end

fprintf(fid,’\n’);

end
CHAPTER 6. EXPORTING AND IMPORTING DATA 35


>> fclose(fid);

>>

6.2.2 Reading from keyboard


For this task we have the nice command ”input”, which displays a little message and waits for the
user to type in some data. The syntax is ”a=input(message)” and the data which have been typed
in up to the first return are passed on to a. As a small example, we store the following code


1 a = input(’Enter a number 0 );

2 w = input(’Enter a word’);

3 for i = 1 : a

4 fprintf(’%s \n’,w);

5 end;

6

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

>>

6.2.3 Reading from a file


As discussed earlier we can open a file for reading in some ASCII data using ”fid = fopen(name,’r’)”.
To read in the data we can apply several Matlab commands depending on how the data are
structured. A command which works independently of the structure is the ”fscanf” command.
However, if the data are written in matrix format, it is easy to import them using the ”load”
command.


>> clear

>> load Daten3

>> who

>> load(0 pores 1.mtx0 )

>> C=spconvert(pores 1)

>> size(C)

30 30

>> full(C)

>>

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)

>>

6.3 Importing and Exporting Data from/to Databases


This is a common problem when analyzing data, however there is no single tool which helps for all
databases and worse they are all not an integral part of Matlab.
As an alternative one can try to write out the wanted data from the database in ASCII format
and read them in as above described and vise versa for exporting the data.
For some databases there exist Matlab database tools, which are either part of a toolbox or
might be downloadable from the web.

6.4 A detailed example


Often when documenting research result data tables are included within a text document. In case
the text document is written in LATEX then including a table is a bit laborious. In the following
we present a function which automatically writes a file containing LATEX code for a table.
As an example data table we use
Title
A B C
a 3 4 7
b 17 -1 5
c 3 -4 2
The corresponding LATEX code has the form


1 \begin{tabular}{|l| ∗ {3}{c|}} \\ \hline

2 & \multicolumn{3}{c|}{Title} \\ \hline

3 & A & B & C \\ \hline

4 a & 3 & 4 & 7 \\

5 b & 17 & -1 & 5 \\

6 c & 3 & -4 & 2 \\ \hline

7 \end{tabular}

8
CHAPTER 6. EXPORTING AND IMPORTING DATA 37

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.

graphs plot plot3


log scale graphs semilogy semilogx loglog
diagrams bar stairs pie
”stem” graphs stem stem3
contours contour contourf contour3 pcolor
surfaces surf surface surfc mesh
waterfall
others line fill fill3 image
scatter scatter3 plotmatrix spy

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.

zlabel Legend of the z-achis: Writes a label next to the z-achis.


text Arbitrary comments and texts: Writes the user specified text at the user specified coordinate.
colorbar Table of the used colours: Provides next to the plot a scala with the colourscheme being
used for the current plot.
colormap Specifies the colour map: To change the colour profile one can pass to colourmap a
colour coding.
colormenu Menu for colour tools: Enables an additional menu in the graphical window. Here
many fancy options can be set.
shading Colour shading: Changes the interpolation Matlab uses for colour plots like ”pcolor”.
The standard setting is ”shading flat”, also available is ”shading interp” for interpolating the
data and ”shading faceted”.
close Closing windows: The command ”close(figure(1))” closes the graphic window figure 1 in
case it has been open.
view Changing point of view: To change the point of view in a three dimensional plot the command
view provides able help.

7.2 The plot command


Common to all graphical commands is that they behave differently on the number of input variables,
their datatype and their format. We explain some of these effects using the ”plot” command.
Several commands behave exactly the same way as this command, for example the logarithmic
plots.

7.2.1 plot with one argument


Calling ”plot(data)” opens the graphic window figure 1 if not already opened and unless a different
graphic window has been activated using ”figure(number)” or the mouse button. The content of
the active graphic window is lost unless it had been frozen using ”hold on”.
CHAPTER 7. GRAPHIC 41


>> x = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12]

>> plot(x)

>> plot(sin(x))

>>

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.

7.2.2 The plot command using two arguments


Here we have two distinctive possibilities to call plot


>> x = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12]

>> plot(x, sin(x))

>> plot(x0 , sin(x0 ))

>> plot(sin(x),0 r+0 )

>>

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

Numerical linear algebra tools

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.

8.1 Full matrices


We already discussed part of this in earlier chapters, but to have a better reference we recall those
here again together with some new functions.

8.1.1 Defining matrices


zeros null matrix ones all ones
eye identity matrix rand random matrix, equally distributed
randn random matrix, normal distributed diag diagonal matrix
compan companion matrix kron Kronecker product

”gallery” provides about 40 different special matrices, like Wilkinson famous matrices.

8.1.2 Calculating with matrices


A+B addition A-B subtraction
0 0
A transposition and A. transposition
complex conjugation
A b2 power A*B multiplication
A\B solves AX = B A/B solves XA = B
A.*B element wise multiplication A./B element wise division
expm(A) matrix exponential function logm(A) matrix logarithm
sqrtm(A) square root of a positive defi- inv(A) inverse of A
nite matrix
norm matrix norm cond condition number
max row/column maxima min row/column minima
sort sorts row/column-wise sum row/column sum
trace trace of a matrix det determinant
null null space of a matrix orth orthonormal base

44
CHAPTER 8. NUMERICAL LINEAR ALGEBRA TOOLS 45

If A is square then ”expm(A)” is defined as


X

1 k
expm(A) = A .
k!
k=1

So only if A is a scalar or a diagonal matrix, we have expm(A) = exp(A).


Further matrix functions are listed by ”help elfun”, ”help elmat” and ”help matfun”.

8.1.3 Matrix decompositions


One important task is to calculate so called normal forms, decompositions or factorisation of a ma-
trix. Most of these methods are nicely explained in Demmel ”Applied numerical linear Algebra”,
Golub and van Loan ”Matrix Computations” and Watkins ”Fundamentals of Matrix Computa-
tions”.

lu LU-decomposition: The factorization is based on Gaussian elimination using row pivoting to


construct matrices L, U and P with LU = P A. To get all three matrices, the functions needs
to be called as ”[L,U,P]=lu(A);”. If the user asks for ”[Z,U]=lu(A);” then Z = P T L.
qr QR-decomposition: This function returns the QR factorisation of a matrix, where Q is an or-
thogonal and R an upper right matrix. If the real n×m matrix A is non square ”[Q,R]=qr(A)”
returns a square n × n matrix Q thus spanning the entire Rn . In order to solve least
square problems one can use the ”lean” QR decomposition with ”[Q,R]=qr(A,0)”, where
span(Q) = span(A). To Update the QR decomposition there Matlab provides the com-
mands ”qrinsert”, ”qrdelete” and ”qrupdate”.
chol Cholesky decomposition: This is a special case of the LU decompostion for symmetric pos-
itive definite matrices only. Hence it can make use of the structure to save memory and
computation.
eig Eigenvalue decomposition: Calculates eigenvalues of a diagonalisable matrix. ”[V,D] = eig(A)”
returns also the eigenvectors V , here the eigenvalues are along the diagonal of D. The ordering
in D and V match, that is A = V ∗ D ∗ inv(V ). A word of caution with respect to this tool
if the matrix A is not normal, in this case the Jordan decomposition (which is calculated by
eig) can be unstable and a better tool is ”schur”.
schur Eigenvalue decomposition: In case of normal matrices it should be equivalent to ”eig”,
however for nonsymmetric matrices ”schur” is more stable. The Schur decomposition has
the form A = Q ∗ R ∗ QT .
svd Singular value decomposition: This command returns a factorisation of the form A = U ∗S ∗V 0
where U and V are orthogonal and S is diagonal with nonnegative entries sorted in decreasing
order. Singular values are for example important in model reduction.
diag Diagonal: Applied to a matrix, ”diag” returns a vector containing the diagonal elements of
A. However when applied to a vector it constructs a matrix with the vector elements along
its diagonal while the remaining matrix elements are zero.
tril Triangle below diagonal: Returns a matrix which has the same entries below the diagonal as
the original matrix but zeros along and above the diagonal.
triu Triangle above diagonal: Returns a matrix which has the same entries above the diagonal as
the original matrix but zeros along and below the diagonal.


>> A=rand(5)+10*eye(5)

>> eig(A)

>> B = A+A0
CHAPTER 8. NUMERICAL LINEAR ALGEBRA TOOLS 46


>> eig(B)

>> C = sqrtm(B);

>> [V,D] = eig(B);

>> E = diag(sqrt(diag(D)));

>> F= C-V*E*V 0

>>

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;

>>

8.2 Sparse matrices


In many applications the arising matrices are large if not huge and have few entries often with some
pattern. For such matrices the use of a sparse matrix format is important as it saves memory and
computation. Such a format is readily implemented in Matlab and most routines and calculation
work with this format as with the full format. However a few methods need there special tools,
this is not just based on the fact that the other methods could not be applied but that the actual
problem to be solved shifts. For example there is usually no need to calculate all eigenvalues of a
million by million matrix, but the leading ten eigenvalues might be desired. Hence we need some
further routines for sparse matrices.

8.2.1 Constructing sparse matrices


sparse Conversion to sparse matrix: ”sparse(A)” returns the original matrix A but in sparse
format. The format consists of three numbers (row,column,value) for each nonzero entry in
A. If m and n are positive integer then ”sparse(m,n)” returns a sparse matrix with m rows
and n columns where all entries have the value zero. Thus the variable just knows that it is
a sparse matrix of this format and does not need to store any further information.
speye Sparse identity matrix: The difference between ”eye(n,m)” and ”speye(n,m)” is their mem-
ory efficiency.
spdiags Sparse matrix with diagonal structure: Many sparse matrices have some kind of diagonal
structure. In order to allow a fast and easy way to define them one can specify which diagonals
shall be set. Calling ”A = spdiags(entries,where,m,n)” constructs an m × n sparse matrix.
The vector where contains indices to the diagonals. The main diagonal has the value zero
all diagonals above have a positive index and all below a negative. The magnitude of the
index value increases one by one starting with the main diagonal. Now the matrix entries is
interpreted as a collection of column vectors, where each column is placed along the diagonal
according to the entries in where.
CHAPTER 8. NUMERICAL LINEAR ALGEBRA TOOLS 47

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

>>

8.2.2 Iterative methods for linear systems


pcg Preconditioned Conjugate Gradient: One of the most popular method for solving linear sys-
tems when the matrix is a general sparse positive definite matrix. The method reduces the
error in the operator norm.
cgs Conjugate Gradient Squared: This is a generalisation of ”pcg” to matrices which are still
symmetric but no longer positive definite.
minres Minimum Residual: Another method for symmetric linear systems, here the residual is
minimized.
gmres Generalized Minimum Residual: Probably the most popular method for solving linear
systems when the matrix is nonsymmetric.


>> A = spdiags(ones(100,1)*[-1,-1,5,-1,-1],[-20,-1,0,1,20],100,100);

>> b = rand(100,1);

>> y = A \ b;

>> D = diag(diag(A));

>> x = b;

>> for i = 1:20

x = D\((D-A)*x+b);

end

>> tol = norm(y-x)

>> z = pcg(A,b,tol);

>> tol = norm(y-z)

>>

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?

Aufgabe 8.3 Given the least square problem

min kAx − bk2 . (8.1)


x

You might know that the linear system

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.

See Chapter 10 for a practical example.

9.4 Other functions


fzero Root finding for nonlinear scalar functions: ”fzero(fun,start)” searches for a zero of the
nonlinear function fun. If start is a pair of values , say a and b, for which f un(a) ∗ f un(b) < 0
holds then fzero safely finds a zero.
fminsearch Multidimensional search for a minimal point: ”fminsearch(fun,start)” searches for a
local minimizer if the function has the form f un : Rn → R.

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

>>

9.5 Ordinary differential equations


A standard task in applied maths is to solve some initial value problems, that are problems of the
form
du
= f (t, u) u(0) = u0
dt
for which Matlab provides the functions
ode113 ode15i ode15s ode23
ode23s ode23t ode45
Above methods combine several numerical ideas to counter some of the intrinsic complications
initial values problems often have. Further these methods can be fine tuned using some optional
parameters.
As an example the methods ”ode23s” and ”ode15s” are specialised tools for stiff problems,
which are an important subclass of initial value problems.
Consider the problem
   
−0.1 1 1
u̇ = u u(0) = (9.1)
−1 −0.1 0

which has the exact solution


 
cos(t)
u(t) = e−t/10 . (9.2)
−sin(t)

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

uxx + (1 − u)(1 + u2x )3/2 = 0 u(−1) = u(1) = 0.

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

9.6 Partial differential equations


Partial differential equations are important in many applications. While few of these problems can
be solved explicitly, many more can be easily approximated numerically. One simple problem is
the heat equation

∂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

pa (x, t, u) + qa (x, t)F (x, t, u, ux ) = 0

for the left boundary x = a and

pb (x, t, u) + qb (x, t)F (x, t, u, ux ) = 0

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

10.1 Random number generator


In many scientific problems large amounts of random numbers are required. However a computer
is never able to produce random numbers, only sequences of pseudo random numbers which appear
to be random but are deterministic. One important effect for scientific research is, they can be
reproduced.
As the random numbers are important there are many ideas how to create them such that
they have good probabilistic properties. Nevertheless some quite poorly behaving random number
generators are still in widespread use. Here we provide a code which illustrates some of the problems
when designing pseudo number generators.
One standard class of pseudo random number generator are linear congruence methods which
use the operation
Xi = (a ∗ Xi−1 + b) mod M.
This is a reasonable pseudo number generator if only a single equally distributed random number
is needed.


1 % linear congruence method

2 %

3 % Y = congruence (N,A,B,M,S)

4 % returns N equally distributed values in the interval (0,1).

5 % The input variables A, B and M are the parameters of

6 % the pseudo number generator and the seed S is used if

7 % specified, otherwise an internal state value is used.

8 %

9 % If congruence is called for the first time and S is not

10 % specified then S=round(M/3+1).

11 %

12 function Y = congruence (n,a,b,M,S,varargin)

13 global congX

14 if (nargin < 4)

15 fprintf(’Not enough input variables\n’);

16 Y = -1;

17 return

18 end

19 if (nargin<5)

20 if isempty(congX)

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

Now we can compare the methods easily




>> wanted=struct(’mean’,1/2,’variance’,1/12,...

’skewness’,0,’kurtosis’,1.8,...

’median’,1/2,’corr’,0);

>> f = @(n) congruence(n,2,0,11);

>> GenTest(f,100,2)

>> f = @(n) congruence(n,1229,1,2048);

>> GenTest(f,100,2)

>> f = @(n) Fibonacci(n);

>> GenTest(f,100,2)

>> GenTest(f,1e4,17)

>> f = @(n) rand(n,1);

>> GenTest(f,1e4,2)

>>

You might also like