An Intro to Matlab

59
An introduction to Matlab J. Berns-M¨ uller September 26, 2006

Transcript of An Intro to Matlab

Page 1: An Intro to Matlab

An introduction to Matlab

J. Berns-Muller

September 26, 2006

Page 2: An Intro to Matlab

Contents

1 Introduction 41.1 General Remarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.1.1 What is Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.1.2 Why might Matlab be useful . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.2 First Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.2.1 Demo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.2.2 Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

1.3 Literature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.4 Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2 Numbers and Matrices 82.1 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2 Definitions of numbers, vectors and matrices . . . . . . . . . . . . . . . . . . . . . . 8

2.2.1 numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2.2 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.2.3 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.3 Working with matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.3.1 Matrix versus vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.4 Matrix Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.4.1 Unitary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.4.2 Binary Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

2.5 Matrices, Functions and Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.5.1 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.5.2 Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.5.3 Some standard functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.5.4 Further Matrix Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

2.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

3 Script and Function Files 163.1 General . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163.2 Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163.3 A first script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163.4 Template for script files – hand in homework . . . . . . . . . . . . . . . . . . . . . 173.5 A first function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183.6 Inline-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

3.6.1 Subfunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203.7 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

1

Page 3: An Intro to Matlab

CONTENTS 2

4 Conditional Statements 224.1 Branching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

4.1.1 Branching with if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224.1.2 Branching with switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234.1.3 Searching with find . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

4.2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244.2.1 The fixed loop for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244.2.2 The conditional loops while . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

4.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

5 Other data types 275.1 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275.2 Structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285.3 Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285.4 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295.5 Working with strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305.6 Working with blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

6 Exporting and Importing Data 336.1 Saving and reading of Matlab data . . . . . . . . . . . . . . . . . . . . . . . . . . 336.2 Export and Import of ASCII Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

6.2.1 Writing ASCII data to a file . . . . . . . . . . . . . . . . . . . . . . . . . . . 346.2.2 Reading from keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356.2.3 Reading from a file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

6.3 Importing and Exporting Data from/to Databases . . . . . . . . . . . . . . . . . . 366.4 A detailed example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

7 Graphic 397.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397.2 The plot command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

7.2.1 plot with one argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407.2.2 The plot command using two arguments . . . . . . . . . . . . . . . . . . . . 41

7.3 Movies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427.4 Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

8 Numerical linear algebra tools 448.1 Full matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

8.1.1 Defining matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448.1.2 Calculating with matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448.1.3 Matrix decompositions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

8.2 Sparse matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468.2.1 Constructing sparse matrices . . . . . . . . . . . . . . . . . . . . . . . . . . 468.2.2 Iterative methods for linear systems . . . . . . . . . . . . . . . . . . . . . . 47

8.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

9 Numerical Methods 499.1 Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499.2 Quadrature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509.3 Probability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519.4 Other functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519.5 Ordinary differential equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529.6 Partial differential equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Page 4: An Intro to Matlab

CONTENTS 3

9.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

10 Examples 5510.1 Random number generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

Page 5: An Intro to Matlab

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 ofthe most widespread mathematical programming platforms. Here we just consider the basic partof 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 18D-52064 Aachen

Phone: 024147075-0Fax: 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 softwaredevelopment 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

Page 6: An Intro to Matlab

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 specialapplications. Many of them are specialized for a specific area of mathematics. Matlab is noexception, it is not designed to do analytical or axiomatic calculations. Matlab was originallydesigned for Numerical Linear Algebra and its Applications and has grown now into Numericalprogramming and its Applications.

The following lest of mathematical packages and libraries is not exhaustive and for examplemany 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 thedevelopment center or matlab -nojvm to get the Matlab shell. Matlab can be started fromany directory, actually it makes sense to create several directories and subdirectories to work withMatlab, as one creates various files containing data or Matlab-functions.

Starting the Matlab development center one usually gets several windows, one of which is thecommand window. This command window and the Matlab editor will be the main tools, theremaining windows can be deleted without any worry. In case we need one of these windows wecan 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 problemsare more complex we will see later how we can write scripts and functions. But we start with theMatlab prompt.

The probably most important command at least when working with the Matlab shell isthe ”exit”-command. Otherwise the command ”help” will be one of the most frequently usedcommands, as the online help function is extremely helpful.

Page 7: An Intro to Matlab

CHAPTER 1. INTRODUCTION 6

1.2.1 Demo

To get started Matlab provides several demos demonstrating how Matlab works ranging fromintroductory 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 beenpressed). 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 theuser 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 correspondinghelp 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 thecommand ”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 andspecially many books on how to use additional packages. This course together with the online helpshould provide a good start for working with Matlab. Hence we do not suggest to buy one of thefollowing books, however in case you like to have an additional source these are recommendablebooks.

Getting started:

Rudra Pratap Getting Started with Matlab (Oxford)

Duane Hanselman & Bruce Littlefield Mastering Matlab (Prentice Hall)

Starting, but generally more advanced:

Page 8: An Intro to Matlab

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 manygraphical commands that we can not cover them all, and specially not all their options. Howeverin 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 thecommand ”help help”.

Aufgabe 1.2 Please type the commands ”help” and ”help ops”. (Here you find a summary of allthe Matlab math operators.)

Aufgabe 1.3 Please try the following sequence of commands∣∣∣ >> clear∣∣∣ >> area= pi*r∣∣∣ >> r=2;∣∣∣ >> area=pi*r2∣∣∣ >> area∣∣∣ >> area = @(r) pi*r 2∣∣∣ >> 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 besolved in Matlab.

Given the initial value problem

(d

dt

)2

x(t) = −x(t) x(0) = 1.

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

Page 9: An Intro to Matlab

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 arethey needed explicitly in standard applications. The reason for the later is based in the automaticdatatype conversion and the automatic memory allocation. However if you like to learn more aboutother 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 commandline.

a Variable names: Here a is a name of a user defined variable. Variable names start with aletter and may contain numbers and the underscore. Matlab itself distincts between smalland capital letters, however if your system does not some internal Matlab variables andfunctions might not be case sensitive.

= Assignment: With assigning a value to a variable all previous information of this variable suchas datatype, size and content are lost. The new variable a has now the type, size and contentaccording 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 ofthe command and secondly suppresses the result. If you like to mark the end of a commandbut like to see the result you can use the comma or the [Return]-key. In case you like to writemore than one command into one line you need to use either the comma or the semicolon toseparate the commands.

8

Page 10: An Intro to Matlab

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 andcomplex 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 complexnumbers, so ”i”, ”j” and ”1i” are all the same number, the imaginary unit. Only the last form isrecommended 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 outputformat is short. For more on the output format see ”help format”. Changing the output formathas now effect on the internal working accuracy.

Further the two values NaN (not a number) and inf (infinity) are treated as special numbers,so that one can do calculations with inf and NaN , however the result is likely to be NaN .

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 isgiven by the use of comma and semicolon. The comma is used to separate two columns andthe semicolon to separate two rows. As above the definition has to be row wise not columnwise.

The semicolon within the square brackets has a different meaning than the semicolon at theend of a command.

∣∣∣ >> A∣∣∣ ans =∣∣∣ 1 2 3∣∣∣ 4 5 6∣∣∣ 7 8 9∣∣∣ 10 11 12∣∣∣ >>

Page 11: An Intro to Matlab

CHAPTER 2. NUMBERS AND MATRICES 10

As all values in the matrix are integers the matrix is presented as a matrix of integer. In generalthe matrix is presented as a matrix of that class of numbers which contains all numbers presentedin 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 possibilitiesto 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 beused 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([ ])∣∣∣ >>

Page 12: An Intro to Matlab

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 positiveintegers, 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 beingthe 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 accessmatrix 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), weneed the corresponding single indices which are provided by the function ”sub2ind”. The oppositeaction 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 matrixsimultaneously

Page 13: An Intro to Matlab

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 dueto two effects. First, Matlab interprets each line before it evaluates it, and the simultaneousstatement needs only one interpretation. Second, the blas routines used within Matlab allow fastactions of of vectorized expressions.

2.4 Matrix Operation

Here we distinct (a bit artificially) between unitary and binary operators. Unitary operators actonly 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.

.′ Transposition: ”B = A.′” assigns the transpose of A.

′ Transposition and complex conjugation: ”B=A′” assigns the transpose and complex conjugate ofA.

Examples∣∣∣ >> A = [1, 2, 3; 4, 5, 6; 7, 8, 9; 10, 11, 12]∣∣∣ >> B = A′∣∣∣ >> C = A.′∣∣∣ >> A(1, 1) = 1 + 2i∣∣∣ >> D = A′∣∣∣ >> E = A.′∣∣∣ >> 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 .

′ is mathematically correct for real matrices, often the use of ′ 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 caseof 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 = A′ ∗ A;∣∣∣ >> D = B − A;∣∣∣ >> a = [1 : 4];∣∣∣ >> E = a′ ∗ a;∣∣∣ >> f = a ∗ a′;∣∣∣ >> G = C 2∣∣∣ >>

Page 14: An Intro to Matlab

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. 2∣∣∣ >> B=A./A∣∣∣ >> C=A.*A∣∣∣ >>

Further, Matlab provides the solution operators ”\” and ”/” for the linear equations Ax = band xA = b. Consider the linear equation Ax = b where A and b are known and x shall becalculated∣∣∣ >> b = [1 : 4]′∣∣∣ >> 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 nowpresent 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

Page 15: An Intro to Matlab

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 cotasin acos atan acotsinh cosh tanh cothasinh acosh atanh acoth

and the next ones work in 360 degrees

sind cosd tand cotdasind acosd atand acotd

For large arguments it is sensible to work in degrees as then the numerical evaluation is moreprecise, as indicated by the following example

∣∣∣ >> sin(pi)∣∣∣ >> 3e12 - 3*10 12∣∣∣ >> 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 inChapters 8 and 9. The following function interpret a given matrix as an array and applies thefunction 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 eitheras 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 ′fro′.

2.5.4 Further Matrix Operation

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

fliplr column permutation flipud row permutationrot90 rotation of a matrix permute permutation of the coordinate systemipermute Inverse of ”permute” reshape general change of shape

(The commands ”permute” and ”permute” are not the standard math permutations but theypermute the coordinates.)

Page 16: An Intro to Matlab

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.

Aufgabe 2.3 What does√

17−5

e3−5equal?

Aufgabe 2.4 Evaluate the solution of the linear system

1 2 1 02 3 2 11 2 4 20 1 2 3

x =

1111

.

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 byapplying the Matlab-functions ”zeros” and ”ones”. Control the size of these matrices with thecommand ”size”.

Aufgabe 2.7 Design a 10 × 5 and a 12 × 6 matrix with random elements. To get a third matrixtake the first 25 elements of the first and the last 15 elements of the last such that the third matrixhas 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)”.

Page 17: An Intro to Matlab

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 variablesdefined 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 (canbe 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, thedisadvantage is they need more memory as variables transfered to the functions are implicitlycopied. 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 toshow 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(′A first Script′);

2∣∣∣ clear

3∣∣∣ who

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

16

Page 18: An Intro to Matlab

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 useof your scripts and functions you can write some comments at the top of your file. The first linein known as H1-line and enables keyword search using the ”lookfor” command. So in this line youshould place some useful keywords. All leading comment lines, that are lines which start with acomment, are interpreted by the ”help” command as help text. The leading ”%” will be deletedby 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 thecommand 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 needto 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

Page 19: An Intro to Matlab

CHAPTER 3. SCRIPT AND FUNCTION FILES 18

4∣∣∣ surname = ′Sharp′;

5∣∣∣ firstname = ′Bob′;

6∣∣∣ course = ′Matlab′;

7∣∣∣ sheet = 1;

8∣∣∣

9∣∣∣ %%%%%%%%%%%%

10∣∣∣ % Do not change these lines

11∣∣∣ file=sprintf(′%s %s %d′,surname,firstname,sheet);

12∣∣∣ delete(file);

13∣∣∣ diary(file);

14∣∣∣ fprintf(′Name: %s, %s\n′,surname,firstname);

15∣∣∣ fprintf(′%s %d\n′,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 changethe 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 fileis 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.

Page 20: An Intro to Matlab

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 textwithin 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 theMatlab function is case sensitive. Further note that the name of the function as writtenwithin 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 fileas a Matlab function. Basically the function declaration consists of five parts, first thefunction command, second the output list, third the assignment sign (=), fourth the nameof 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 thefunction follows the convention for the names of variables, starting with a letter followed upby 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 nameof the variable is enough. Otherwise the out-list needs to be enclosed by a pair of squarebrackets. 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 variablesand it certainly does not return any value.

The name of the variables being used in the function definition and the code might differfrom the name being used in the help area, however this might upset people checking yourcode. 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 andout-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 passedto the function, for example see plot, and asked as a return, for example see lu. In order toallow a variable parameter length, the last element in the in-list needs to be varargin andvarargout respectively for the out-list. Then the variables nargin and nargout are defined andcontain the number of variables the user passed on to the function or respectively requiredas a return.

3.6 Inline-Functions

There are three ways to define simple math functions, first we could write an M-file, we can usethe ”@” command or we could use the ”inline” command

∣∣∣ >> q=@(x)x.2-3∣∣∣ >> q(3)∣∣∣ >> x=[-3:0.1:3];

Page 21: An Intro to Matlab

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(′x. 2-3′,0)∣∣∣ >> p(pi) - q(pi)∣∣∣ >>

@ Function definition: The command ”@(parameter list) formula” provides an easy way to definesimple functions. Here the parameter list consist out of those variables one likes to pass onand 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 detecta value X for which the function is zero. In case initial is a scalar, the function starts fromthis value, however if initial is a set of two values, say initial = [a, b] then fzero requires thatthe function, say f(x), satisfies f(a) ∗ f(b) < 0. In this case fzero will always succeed anddetermine a value x.

hold Freezing current plots: The command ”hold on” freezes the current plots, so that the followingplotting commands are added to the current one. To reverse the freezing type ”hold off” orsimply 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 firstone, 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 canprovide 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,′−′);

Page 22: An Intro to Matlab

CHAPTER 3. SCRIPT AND FUNCTION FILES 21

16∣∣∣ hold on;

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

3.7 Debugging

Standardly when programming one makes mistakes in the code and finding them afterwards canbe 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, thatare points where Matlab stops the execution of a file, can be done by pressing the left mousebutton on the corresponding line number in the editor window. By doing so Matlab sets a redpoint 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 functionfile needs to be started from the command line.

Once a break point is reached the Matlab prompt in the command window chances to indicatethat 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 thevalues of all current variables, and can do some manipulations with them. From the first breakpoint on we can decide to go step wise or continue till the next break point, we can add and deletebreak 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 thefile 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 happensnow if you type ”cd” in the command window? Next type ”cd=1” and ”who”. What happens nowif you type ”cd” in the command window? Now type ”clear cd” and ”!rm cd.m”, what is the effectof these two commands? (In case of a Windows machine exchange ”!rm cd.m” by ”!del cd.m”)

Page 23: An Intro to Matlab

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 commandsas the user wishes until the ”end” command which finishes the if statement. The block mighthave several ”elseif (condition)” statements as the user likes, however care must be taken on theirordering. Finally there might be one ”else” command. Any sub-block started by if, ifelse and elsecan be followed by any number of Matlab commands and ends with the next elseif, else or endstatement.

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

Page 24: An Intro to Matlab

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. Whileboth programs provide the same result they differ with respect to their number of if blocks. Thefirst example uses one (extended) block while the second one uses two (simple ones), an inner andouter statement.

A condition is a boolean expression, that is, the statement is either true or false. In Matlab thevalue for false is ”0”, any other value is considered as being true. The following boolean operationsare provided

∼ a not aa&b a and ba|b a or b

and(a, b) a and bxor(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 haveseveral 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,

Page 25: An Intro to Matlab

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 themaccording to some indicator. Matlab provides with the ”find” command a very useful tool forthis task.

find Vectorized query: ”find(condition)” returns the indices of the vector/matrix for which thecondition 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 arestill 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. Afirst simple example for a for loop

1∣∣∣ for i = 2 : 10

2∣∣∣ b(i) = i;

3∣∣∣ end;

4∣∣∣ c = [1 : 10]′;

5∣∣∣

The vectors b and c differ only in their first element. As Matlab first evaluates the vector forwhich the loop need to be run, that is all values for i = [2 : 10], it is also possible to use negativenumbers, 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∣∣∣

Page 26: An Intro to Matlab

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 thevalue 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 examplepresents 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(′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 remainingcommands in the loop are not executed and the loop condition is ignored. In case the loopis 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 areignored, Matlab goes back to the start of the loop and continues the loop with the nextcycle.

return exit M−file Strictly speaking this is not a loop command, however it gets almost only usedwithin a loop, especially in an inner loop if all loops should be stooped. As this commandaborts the execution of commands within an M-file the command should be preceded bycommands 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 2+j 2-(i*j);

5∣∣∣ end

Page 27: An Intro to Matlab

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 returnsall 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 thevariable is a positive integer it shall return n!. If the input value is not an integer an error messagewould 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 twoinput arguments. If the input variables are non integers or not enough input arguments have beenpassed 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)”.

Page 28: An Intro to Matlab

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 bysingle quotes, ”′”, for example ”’hello’”. Due to the automatic type conversion we do not need toallocate memory nor do we need to define string variables. Some more examples for strings

∣∣∣ >> A = [3, 4] % this is a matrix∣∣∣ >> A =′hello world ′ % now A is a string∣∣∣ >> B = [′hello ′,′world ′]∣∣∣ >> B(1)∣∣∣ >> B(2)∣∣∣ >> B(1 : 5)∣∣∣ >>

The second assignment ”A=′hello world ′” 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 accessto strings and several ways to concatenate strings. When concatenating two strings there is noadditional sign in between the two strings.

∣∣∣ >> C =′345 ′∣∣∣ >> C(1)∣∣∣ >> C(2)∣∣∣ >> C(1) ∗ C(3)∣∣∣ >>

The output format is ambiguous, we can not see clearly whether the output from line two andthree 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 typestring, we obtain a numerical value with C(1) ∗ C(3). As multiplication is not a string operationbut a matrix operation the two values C(1) and C(3) are interpreted as being of type matrix andthere value is determined using the ASCII table.

The opposite effect occurs in

27

Page 29: An Intro to Matlab

CHAPTER 5. OTHER DATA TYPES 28

∣∣∣ >> D = [′hello ′,59,45,41]∣∣∣ >>

Here the numbers 59, 45, and 41 are interpreted as characters getting the corresponding char againusing the ASCII table.

Explicit type conversion is more readable than the implicit conversion. Implicit type conversionis 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”, speciallyfor advanced options. The advantage of this datatype is it can carry various components whichhave their own name, thus the ordering of the information is unimportant. For these componentnames the standard name convention applies.

∣∣∣ >> A.type=′matrix ′;∣∣∣ >> A.size=[3,2];∣∣∣ >> A.content=[1,2;3,4;5,6];∣∣∣ >> A∣∣∣ >> A.type∣∣∣ >> A.content∣∣∣ >> B=struct(′type ′,′matrix ′,′size ′,[3,2],′content ′,[1,2;3,4;5,6]);∣∣∣ >> C=[struct(′type ′,′matrix ′,′size ′,[3,2],′content ′,[1,2;3,4;5,6]);...∣∣∣ >> 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 toconstruct and simultaneously name some components if not all of this newly formed variableand simultaneously initialize these components.

isfield(S,′name ′) components test: tests if a certain component, name, is part of the struct S.

S=getfield(S,′name′) Access: this is a more complicated form for ”S.name”, however in case ofprogramming with arbitrary and unknown options this is quite useful.

S=setfield(S,′name′,wert) Assigning: this is a more complicated form for ”S.name=wert”.

S=rmfield(S,′name′) Remove component: Removes the specified component, if it is the lastcomponent, 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 ascontent, this variable can have any datatype, matrix, string, struct and cell. The cells elementscan differ in datatype and size.

Page 30: An Intro to Matlab

CHAPTER 5. OTHER DATA TYPES 29

∣∣∣ >> A = 1, [2, 3], 4, [5, 6; 7, 8],’hello’∣∣∣ >> A2∣∣∣ >> A5∣∣∣ >> A(5)∣∣∣ >> A4(2, 1)∣∣∣ >> B = 1, [2, 3]; 4,′ hello′∣∣∣ >>

. . . Create cells: This is one way to define cells, simply listing all the variables and data incurly brackets. Two cells in a row are separated by a comma, rows of cells are separatedby semicolon as we are used from matrices. Keep in mind all rows need to have the samenumber 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 valuesas empty.

A. . . Assessing a cell: Matlab distincts between the cell element and its contents. Using thecurly brackets we can assess the cell contents. As the cell contents is a variable, we can domath manipulations or string operations if the datatype of the contents is matrix or stringrespectively.

A(. . .) Assessing cell element: In contrast to the previous way of assessing a cell A(1) is still acell, 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 2, A 3, A 4∣∣∣ >> C = ’hello’,’world’,’What shell we say?′∣∣∣ >> D = A, B; , C∣∣∣ >> D(3)∣∣∣ >> D3∣∣∣ >> D(2)∣∣∣ >> D2∣∣∣ >> D22∣∣∣ >>

5.4 Sets

The datatype cell can be used for set operations, therefore the cell needs to consist of elements withdatatype string only. Further each content is only allowed to appear once, which can be achievedusing the command ”unique”.

Let A and B be sets then the following operations are defined

maths expression Matlab commandA ∪ B union(A, B)A ∩ B intersect(A, B)A\B setdiff(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 ofA and returns the value 1 (true) if so otherwise the value 0 (false).

Page 31: An Intro to Matlab

CHAPTER 5. OTHER DATA TYPES 30

∣∣∣ >> A = ′1′,′ 2′,′ 3′,′ 4′,′ 5′,′ a′,′ b′,′ c′,′ d′∣∣∣ >> B = ′1′,′ A′,′ 2′,′ 4′,′ 4′,′ 4′,′ 5′∣∣∣ >> B = unique(B)∣∣∣ >> B = union(B,′ 7′)∣∣∣ >> D = union(intersect(A, B), ′9′,′ 7′,′ A′,′ B′)∣∣∣ >> if ismember(′3′,D)∣∣∣ fprintf(′We have lost\n′);∣∣∣ end∣∣∣ >>

5.5 Working with strings

There are many functions available under Matlab to modify, read and write strings. Here wepresent 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 returnand provides as a result what ever the user has entered. An empty input is interpreted as a0 × 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 firstjust 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 sortof data,

∣∣∣ >> fprintf(′%f %e\n’,-pi,-pi);∣∣∣ >> fprintf(′%8.4f %8.4e\n’,-pi,-pi);

Page 32: An Intro to Matlab

CHAPTER 5. OTHER DATA TYPES 31

∣∣∣ >> fprintf(′%2.1f %2.1e\n’,-pi,-pi);∣∣∣ >> fprintf(′%+2.1f %2.1E\n’,-pi,-pi);∣∣∣ >>

sprintf formated string: In principle this command works the same way as fprintf but it returnsa 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 stringsstrcmp comparing stringsstrfind searching strings within stringsstrtok splitting strings according to a list of token

More functions to work with strings can be found by calling ”help strings” and ”help strfun”.∣∣∣ >> A = ′hello ′;∣∣∣ >> B = ′world ′;∣∣∣ >> C = ′How ′;∣∣∣ >> D = ′is ′;∣∣∣ >> E = ′life ′;∣∣∣ >> F = ′fine ′;∣∣∣ >> 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. Herewe 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 allthe 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 setsa, and b, d using set operations applied to the set A, B and C.

Page 33: An Intro to Matlab

CHAPTER 5. OTHER DATA TYPES 32

Aufgabe 5.2 Write a function ”Forecast(Weather)”, which works on the data Weather which isa 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 elementin a nicely formated way.

Define Weather with the following data

place temperature rain in mlKoeln 20 0Duesseldorf 19 3Frankfurt 25 0Offenbach 17 10Mainz 21 1Hanau 21 0

and call ”Forecast(Weather)”.

Page 34: An Intro to Matlab

Chapter 6

Exporting and Importing Data

Attention:

Matlab is a nice toolbox to work with even in case of large setsof data. Especially it is straight forward to create huge amountsof data, storing them will eventually if not immediately fill yourdisc.

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,′a′,′b′,′C′)∣∣∣ >>

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

Page 35: An Intro to Matlab

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 toimport for other tools. However most tools allow the import and export of ASCII data. As ASCIIdata can be viewed by most editors one can check the format of the data and then adapt theimportation of those data or simply their interpretation.

In order to read and write ASCII data we have seen already some commands but let us restatethem together with some new ones

fopen Opens and creates files: The command ”fopen(’name’,’action’)” opens the file name eitherfor 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 notexist 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 isanyway truncated to length zero. One can assume that the file has been deleted and createdagain. 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 identifierand 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 thesyntax 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 isagain the file identifier. Additionally the file is closed and any further use of the file identifierfile 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

Page 36: An Intro to Matlab

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 theuser to type in some data. The syntax is ”a=input(message)” and the data which have been typedin 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 ′);

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 arestructured. 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(′pores 1.mtx′)∣∣∣ >> 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 market1

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.

1http://math.nist.gov/MatrixMarket

Page 37: An Intro to Matlab

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 alldatabases 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 formatand 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 ormight be downloadable from the web.

6.4 A detailed example

Often when documenting research result data tables are included within a text document. In casethe text document is written in LATEX then including a table is a bit laborious. In the followingwe present a function which automatically writes a file containing LATEX code for a table.

As an example data table we use

TitleA B C

a 3 4 7b 17 -1 5c 3 -4 2

The corresponding LATEX code has the form

1∣∣∣ \begintabular|l| ∗ 3c| \\ \hline

2∣∣∣ & \multicolumn3c|Title \\ \hline

3∣∣∣ & A & B & C \\ \hline

4∣∣∣ a & 3 & 4 & 7 \\

5∣∣∣ b & 17 & -1 & 5 \\

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

7∣∣∣ \endtabular

8∣∣∣

Page 38: An Intro to Matlab

CHAPTER 6. EXPORTING AND IMPORTING DATA 37

Here the number 3 in rows one and two indicates that there are three data columns. In casea different number of data columns shall be tabled then this must be altered accordingly. Thefollowing 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,′\\begin tabular| l| ∗ %dc|\\\\ \\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 sureyou 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 interfacedescription. 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 linesaccording to some delimeters provided by the user and finally the function shall save the data inanother file. Non of the delimeters (except newline) shall be present in the outfile. The functionshall 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 mighthave 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 .

Page 39: An Intro to Matlab

CHAPTER 6. EXPORTING AND IMPORTING DATA 38

The function shall return a struct having the fieldnames as specified by the file with the matchingcontent.

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

Page 40: An Intro to Matlab

Chapter 7

Graphic

As the graphic tools are one of the key features of Matlab there are a variety of commands dealingwith 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 threedimensions, which have all their own command, ”plot” and ”plot3” respectively. Many of thesecommands 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 plot3log scale graphs semilogy semilogx loglogdiagrams bar stairs pie”stem” graphs stem stem3contours contour contourf contour3 pcolorsurfaces surf surface surfc mesh

waterfallothers line fill fill3 image

scatter scatter3 plotmatrix spy

Additionally there are plenty of commands to change the handling of the graphs or theirwindows.

figure Activating a graphical window: Windows for graphical outputs are called figure plus apositive integer. Calling ”figure(number)” then the corresponding window is activated andin case it did not exist before it is opened. All graphical commands act on the currentlyactivated graphical window.

print Printing to file: With ”print -style name” the content of the currently activated graphicalwindow is printed to the file name. The format which is used for the graphical output canbe 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 formatspecified by style.

hold Freezing of plots: Standardly any plot command deletes all old plots in the currently activatedgraphical window and then plots the new graph. In order to get several plots into onecoordinate system, the graph is frozen using the command ”hold on” and all following plotcommands add their graphs to the same coordinate system. To reverse the freezing type”hold off” or ”clf”.

39

Page 41: An Intro to Matlab

CHAPTER 7. GRAPHIC 40

clf Clear figure: Clears the plots from the currently active graphical window, sets hold to hold offand removes all items, such as texts, labels, lines, etc from the window if they have been setusing Matlab commands instead of graphic menu buttons.

axis Coordinate axis: Standardly Matlab sets automatically the coordinate axis. However thiscan be changed by the user with the command ”axis”. The scaling of the axis are thenupdated automatically.

legend Legend maker: In case there is more than one graph in a coordinate system it is wise tolabel them. This can be achieved with ”legend(name1,name2,. . . ,namek)” which providesstandardly in the top right corner a small box containing the colours used and writing thenames 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 beingused for the current plot.

colormap Specifies the colour map: To change the colour profile one can pass to colourmap acolour coding.

colormenu Menu for colour tools: Enables an additional menu in the graphical window. Heremany 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 thedata and ”shading faceted”.

close Closing windows: The command ”close(figure(1))” closes the graphic window figure 1 incase it has been open.

view Changing point of view: To change the point of view in a three dimensional plot the commandview 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 logarithmicplots.

7.2.1 plot with one argument

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

Page 42: An Intro to Matlab

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 isploted, the entries of the vector data against their indices. If data is a matrix with n columns, thenn graphs are plotted within one coordinate system.

The command ”plot(data)” takes two consecutive elements from the vector data and draws astraight 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 connecta set of values which lie on the exact graph. This leads to the fact that Matlab graphs do notalways 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(x′, sin(x′))∣∣∣ >> plot(sin(x),′ r+′)∣∣∣ >>

The first two results are in principle the same usage, here we only demonstrate that the orientationof the matrices x and y does matter. In contrast the second argument differs in the third plot. Wecan ask plot to use a specific colour and line style to do the plotting. The colours are

blue b red ryellow y green gmagenta 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 xsquares s diamonds d

For further possibilities see ”help plot”.

Page 43: An Intro to Matlab

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 timeor 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];∣∣∣ >> z = sin(y′-1). 2*x. 2+y′. 2*cos(x-3). 2-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(′ Could you spot the minimal point? \n′);∣∣∣ >>

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 storedin slides. The speed is measured in frames per second. Now if repeat is a scalar, then itrepresents how often the movie shall be repeated. In case repeat is a vector, the first entryof repeat has the same meaning as in the scalar case. The remaining vectors are interpretedas indices to the frames, so the film can be played in any order independent of the orderingof slides.

getframe graphic to frame conversion: In order to construct a frame one has to plot and labelthe graph before it is stored as a frame. movie will show this frame exactly as it has beenconstructed 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 entriesin 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);∣∣∣ >>

Page 44: An Intro to Matlab

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 labelsand a title to the graph.

Aufgabe 7.3 The island Neverland recently had an election and the following table provides theresults.

first try 244the winner is 2074best result ever 488always second 1586no chance 110one 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 peoplelike to know how many seats each party got, but attention this island has a 5 % limit, saying partieswho got less than 5% will not get any of the 72 seats. Please make use of the ”text” command inorder to label your plots.

Page 45: An Intro to Matlab

Chapter 8

Numerical linear algebra tools

Like the graphic commands the methods for solving numerical linear algebra problems is a keypart 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 thosehere 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

A′ transposition andcomplex conjugation

A.′ transposition

A 2 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-nite matrix

inv(A) inverse of A

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

Page 46: An Intro to Matlab

CHAPTER 8. NUMERICAL LINEAR ALGEBRA TOOLS 45

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

expm(A) =

∞∑

k=1

1

k!Ak .

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 toconstruct matrices L, U and P with LU = PA. To get all three matrices, the functions needsto 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 R

n. In order to solve leastsquare problems one can use the ”lean” QR decomposition with ”[Q,R]=qr(A,0)”, wherespan(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 andcomputation.

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 orderingin D and V match, that is A = V ∗ D ∗ inv(V ). A word of caution with respect to this toolif the matrix A is not normal, in this case the Jordan decomposition (which is calculated byeig) 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 hasthe form A = Q ∗ R ∗ QT .

svd Singular value decomposition: This command returns a factorisation of the form A = U ∗S∗V ′

where U and V are orthogonal and S is diagonal with nonnegative entries sorted in decreasingorder. Singular values are for example important in model reduction.

diag Diagonal: Applied to a matrix, ”diag” returns a vector containing the diagonal elements ofA. However when applied to a vector it constructs a matrix with the vector elements alongits diagonal while the remaining matrix elements are zero.

tril Triangle below diagonal: Returns a matrix which has the same entries below the diagonal asthe original matrix but zeros along and above the diagonal.

triu Triangle above diagonal: Returns a matrix which has the same entries above the diagonal asthe original matrix but zeros along and below the diagonal.

∣∣∣ >> A=rand(5)+10*eye(5)∣∣∣ >> eig(A)∣∣∣ >> B = A+A′

Page 47: An Intro to Matlab

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 ′∣∣∣ >>

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 usingthese 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 somepattern. For such matrices the use of a sparse matrix format is important as it saves memory andcomputation. Such a format is readily implemented in Matlab and most routines and calculationwork 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 actualproblem to be solved shifts. For example there is usually no need to calculate all eigenvalues of amillion by million matrix, but the leading ten eigenvalues might be desired. Hence we need somefurther routines for sparse matrices.

8.2.1 Constructing sparse matrices

sparse Conversion to sparse matrix: ”sparse(A)” returns the original matrix A but in sparseformat. The format consists of three numbers (row,column,value) for each nonzero entry inA. If m and n are positive integer then ”sparse(m,n)” returns a sparse matrix with m rowsand n columns where all entries have the value zero. Thus the variable just knows that it isa 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 diagonalstructure. In order to allow a fast and easy way to define them one can specify which diagonalsshall 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 zeroall diagonals above have a positive index and all below a negative. The magnitude of theindex value increases one by one starting with the main diagonal. Now the matrix entries isinterpreted as a collection of column vectors, where each column is placed along the diagonalaccording to the entries in where.

Page 48: An Intro to Matlab

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 theerror in the operator norm.

cgs Conjugate Gradient Squared: This is a generalisation of ”pcg” to matrices which are stillsymmetric but no longer positive definite.

minres Minimum Residual: Another method for symmetric linear systems, here the residual isminimized.

gmres Generalized Minimum Residual: Probably the most popular method for solving linearsystems 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 overviewon Krylov methods for solving linear systems see the book by Youcef Saad, ”Iterative Methods forSparse Linear Systems”. However, besides Krylov methods there are many other iterative schemesfor solving linear systems.

In many situations iterative methods on their own do not work sufficiently well and require somesort of preconditioning. The Matlab commands ”luinc” and ”cholinc” construct some popularpreconditioners.

8.3 Exercises

Aufgabe 8.1 Define a 200× 200 Matrix A which has the value 2 along its main diagonal and thefirst upper and lower diagonal entries equal to −1. How much memory does this matrix requirein sparse and in full format. (The command ”whos” provides memory information of the currentvariables.)

Page 49: An Intro to Matlab

CHAPTER 8. NUMERICAL LINEAR ALGEBRA TOOLS 48

Aufgabe 8.2 Consider the matrix from Exercise 8.1. Calculate the Cholesky decomposition of thismatrix? Can the Cholesky factor be stored in a more efficient way? Is it possible to construct theCholesky decomposition using ”cholinc”? What happens if you calculate the Cholesky decompositionof the same matrix but now of size 100000× 100000?

Aufgabe 8.3 Given the least square problem

minx

‖Ax − b‖2. (8.1)

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 isto 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 anydifference in the solution?

Page 50: An Intro to Matlab

Chapter 9

Numerical Methods

In contrast to the methods from Numerical Linear Algebra many numerical methods are not partof the core routines. There exist a variety of toolboxes which we do not consider here, whichprovide able tools for specific tasks.

However, of the tools already available within the Matlab core we only discuss a selectionhere.

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 normalisedpolynomial is defined where the first entry corresponds to the highest order of the polynomialand its entry is set to one. The length of the returned vector is one more than the degree ofthe polynomial.

polyval Evaluation of polynomials: ”polyval(p,x)” returns p(y) for all entries y within x. Here pneeds to be the coefficient vector such that the polynomial has the form

zij =

n∑

k=0

pk(xij)k.

roots Roots of a polynomial: This is the inverse function to ”poly” as it calculates the roots of thepolynomial. 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 nota matrix operation in the mathematical sense. ”polyvalm” uses the matrix multiplication andthereby provides the correct result.

polyfit Approximation with polynomials: For a given set of data points, ”polyfit(X,Y,N)” returnsthe 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 satisfysome smoothness properties.

(In fact the result has the datatype piecewise polynomial, however the result is a struct, withthe entry form = ’pp’.)

”spline(X,Y,points)” does not return the coefficients but returns the y-values for the splinesevaluated at points.

49

Page 51: An Intro to Matlab

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 thepolynomials a and b.

∣∣∣ >> % An example: (x)= (x-1). 4∣∣∣ >> 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∣∣∣ >> 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 iteven fails. In order to improve the conditioning one can use three return variables for ”polyfit”, asdone 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.

quad adaptive Simpson: ”quad(f,a,b)” calculates the value of the integralb∫

a

f(x)dx using the

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 schemeis used, which is based upon orthogonal polynomials.

dblquad Two dimensional quadrature: Works similar to ”quad” however now for two dimensionalproblems.

Page 52: An Intro to Matlab

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 equallydistributed 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 columnmeans.

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 experimentswhile 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 thenonlinear function fun. If start is a pair of values , say a and b, for which fun(a)∗fun(b) < 0holds then fzero safely finds a zero.

fminsearch Multidimensional search for a minimal point: ”fminsearch(fun,start)” searches for alocal minimizer if the function has the form fun : R

n → R.

The classical problem of Fourier transformation is also solvable within Matlab which is quitehandy 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)

Page 53: An Intro to Matlab

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 theform

d u

dt= f(t, u) u(0) = u0

for which Matlab provides the functions

ode113 ode15i ode15s ode23ode23s ode23t ode45

Above methods combine several numerical ideas to counter some of the intrinsic complicationsinitial values problems often have. Further these methods can be fine tuned using some optionalparameters.

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

u =

(−0.1 1−1 −0.1

)u u(0) =

(10

)(9.1)

which has the exact solution

u(t) = e−t/10

(cos(t)−sin(t)

). (9.2)

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;∣∣∣ >> 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 + u2

x)3/2 = 0 u(−1) = u(1) = 0.

This problem describes a drop of water. One possibility to solve such problems is to use shootingmethods which reduce this problem to a sequence of initial value problems to be solved. Anotherapproach 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 solverbased on collocation.

Page 54: An Intro to Matlab

CHAPTER 9. NUMERICAL METHODS 53

9.6 Partial differential equations

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

∂ u

∂t=

∂2u

∂x2∀t ∈ [t0, T ], ∀x ∈ Ω.

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

c(x, t, u, ux)∂u

∂t= x−m ∂

∂x(xmf(x, t, u, ux)) + d(x, t, u, ux)

where m = 0, 1 or 2. Here c, d and f are functions depending on space x, time t, current value ofthe unknown u and its spatial derivative ux. In order to work with ”pdepe” we need a function Fwith

F (x, t, u, ux) −→

c(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 valuesshould be provided by a function, say initial, with values = initial(points). Additionally we needboundary 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, ofthe form

bound(xa, ua, xb, ub, t) −→

paqapbqb

,

Note that F and bound need to be defined within M − files as their output need to have threeor 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 thepoints specified in grid, the calculation is carried out! (More points leads to more work and higheraccuracy.)

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 makeuse of the ”help” command.

Page 55: An Intro to Matlab

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 thesolution can be written as u(t) = @(t, x0)exp(A∗ t)∗u0 (”u = expm(A*t) * u” in Matlab). Usingthe 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 odesolvers and we know the exact solution. Approximate the solution by different means and comparethe 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 initialvalues according to u0(x) = 1/(0.1+(x−0.5)2) and boundary condition ux(t, 0) = 0 at the left andu(t, 1) − 10ux(t, 1) = 0 at the right end. Plot the results for times [0 : 0.1 : 1].

Page 56: An Intro to Matlab

Chapter 10

Examples

10.1 Random number generator

In many scientific problems large amounts of random numbers are required. However a computeris never able to produce random numbers, only sequences of pseudo random numbers which appearto be random but are deterministic. One important effect for scientific research is, they can bereproduced.

As the random numbers are important there are many ideas how to create them such thatthey have good probabilistic properties. Nevertheless some quite poorly behaving random numbergenerators are still in widespread use. Here we provide a code which illustrates some of the problemswhen designing pseudo number generators.

One standard class of pseudo random number generator are linear congruence methods whichuse the operation

Xi = (a ∗ Xi−1 + b) modM.

This is a reasonable pseudo number generator if only a single equally distributed random numberis 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

Page 57: An Intro to Matlab

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 asglobal using the command ”global”. This is done here to save the state variable of the pseudonumber generator so that a second call of the pseudo number generator does not return the samevalues. If we use the variable first before we define it as global this will create an error, because thesame variable might be already known outside the function and thus two variables would clash. Asthe command ”global ” already defines the variable either having the content of an outside variablewith the same name or with no content, so being empty. Thus the variable exists but might beempty and hence our check on line 19.

Another class of random number generators are the Fibonacci methods which use

a = Ui − Uj

if a < 0, set a = a + 1Ui = X = areduce i and j by 1if 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 havebeen 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)

Page 58: An Intro to Matlab

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.

mean 1

2variance 1

12

skewness 0 kurtosis 1.8

median 1

2

The following function uses a specified random number generator and calculates above variablesand 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

Page 59: An Intro to Matlab

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

18∣∣∣ M2 = mean( Z. 2);

19∣∣∣ M4 = mean( Z. 4);

20∣∣∣ out.kurtosis = M4/M2 2;

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)′ − 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),′ .′);

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