P. 1
An Intro to Matlab

# An Intro to Matlab

|Views: 34|Likes:

See more
See less

01/12/2014

pdf

text

original

## Sections

• Introduction
• 1.1 General Remarks
• 1.1.1 What is Matlab
• 1.1.2 Why might Matlab be useful
• 1.2 First Steps
• 1.2.1 Demo
• 1.2.2 Help
• 1.3 Literature
• 1.4 Exercise
• Numbers and Matrices
• 2.1 Basics
• 2.2 Deﬁnitions of numbers, vectors and matrices
• 2.2.1 numbers
• 2.2.2 Matrices
• 2.2.3 Vectors
• 2.3 Working with matrices
• 2.3.1 Matrix versus vector
• 2.4 Matrix Operation
• 2.4.1 Unitary Operations
• 2.4.2 Binary Operators
• 2.5 Matrices, Functions and Constants
• 2.5.1 Constants
• 2.5.2 Trigonometric Functions
• 2.5.3 Some standard functions
• 2.5.4 Further Matrix Operation
• 2.6 Exercises
• Script and Function Files
• 3.1 General
• 3.2 Editor
• 3.3 A ﬁrst script
• 3.4 Template for script ﬁles – hand in homework
• 3.5 A ﬁrst function
• 3.6 Inline-Functions
• 3.6.1 Subfunctions
• 3.7 Debugging
• 3.8 Exercises
• Conditional Statements
• 4.1 Branching
• 4.1.2 Branching with switch
• 4.1.3 Searching with ﬁnd
• 4.2 Loops
• 4.2.1 The ﬁxed loop for
• 4.2.2 The conditional loops while
• 4.3 Exercises
• Other data types
• 5.1 Strings
• 5.2 Structs
• 5.3 Cells
• 5.4 Sets
• 5.5 Working with strings
• 5.6 Working with blocks
• 5.7 Exercises
• Exporting and Importing Data
• 6.1 Saving and reading of Matlab data
• 6.2 Export and Import of ASCII Data
• 6.2.1 Writing ASCII data to a ﬁle
• 6.2.3 Reading from a ﬁle
• 6.3 Importing and Exporting Data from/to Databases
• 6.4 A detailed example
• 6.5 Exercises
• Graphic
• 7.1 Overview
• 7.2 The plot command
• 7.2.1 plot with one argument
• 7.2.2 The plot command using two arguments
• 7.3 Movies
• 7.4 Images
• 7.5 Exercises
• Numerical linear algebra tools
• 8.1 Full matrices
• 8.1.1 Deﬁning matrices
• 8.1.2 Calculating with matrices
• 8.1.3 Matrix decompositions
• 8.2 Sparse matrices
• 8.2.1 Constructing sparse matrices
• 8.2.2 Iterative methods for linear systems
• 8.3 Exercises
• Numerical Methods
• 9.1 Polynomials
• 9.3 Probability
• 9.4 Other functions
• 9.5 Ordinary diﬀerential equations
• 9.6 Partial diﬀerential equations
• 9.7 Exercises
• 10.1 Random number generator

# An introduction to Matlab

J. Berns-M¨ ller u September 26, 2006

Contents
1 Introduction 1.1 General Remarks . . . . . . 1.1.1 What is Matlab . . 1.1.2 Why might Matlab 1.2 First Steps . . . . . . . . . 1.2.1 Demo . . . . . . . . 1.2.2 Help . . . . . . . . . 1.3 Literature . . . . . . . . . . 1.4 Exercise . . . . . . . . . . . . . . . . . . . . . . . be useful . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 4 4 4 5 6 6 6 7 8 8 8 8 9 11 11 11 12 12 12 13 13 14 14 14 15 16 16 16 16 17 18 19 20 21 21

2 Numbers and Matrices 2.1 Basics . . . . . . . . . . . . . . . . 2.2 Deﬁnitions of numbers, vectors and 2.2.1 numbers . . . . . . . . . . . 2.2.2 Matrices . . . . . . . . . . . 2.2.3 Vectors . . . . . . . . . . . 2.3 Working with matrices . . . . . . . 2.3.1 Matrix versus vector . . . . 2.4 Matrix Operation . . . . . . . . . . 2.4.1 Unitary Operations . . . . . 2.4.2 Binary Operators . . . . . . 2.5 Matrices, Functions and Constants 2.5.1 Constants . . . . . . . . . . 2.5.2 Trigonometric Functions . . 2.5.3 Some standard functions . . 2.5.4 Further Matrix Operation . 2.6 Exercises . . . . . . . . . . . . . .

. . . . . . matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3 Script and Function Files 3.1 General . . . . . . . . . . . . . . . . . . . . . 3.2 Editor . . . . . . . . . . . . . . . . . . . . . . 3.3 A ﬁrst script . . . . . . . . . . . . . . . . . . 3.4 Template for script ﬁles – hand in homework 3.5 A ﬁrst function . . . . . . . . . . . . . . . . . 3.6 Inline-Functions . . . . . . . . . . . . . . . . . 3.6.1 Subfunctions . . . . . . . . . . . . . . 3.7 Debugging . . . . . . . . . . . . . . . . . . . . 3.8 Exercises . . . . . . . . . . . . . . . . . . . .

1

CONTENTS 4 Conditional Statements 4.1 Branching . . . . . . . . . . . . . . 4.1.1 Branching with if . . . . . . 4.1.2 Branching with switch . . . 4.1.3 Searching with ﬁnd . . . . . 4.2 Loops . . . . . . . . . . . . . . . . 4.2.1 The ﬁxed loop for . . . . . 4.2.2 The conditional loops while 4.3 Exercises . . . . . . . . . . . . . . 5 Other data types 5.1 Strings . . . . . . . . 5.2 Structs . . . . . . . . 5.3 Cells . . . . . . . . . 5.4 Sets . . . . . . . . . 5.5 Working with strings 5.6 Working with blocks 5.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2 22 22 22 23 24 24 24 25 26 27 27 28 28 29 30 31 31 33 33 34 34 35 35 36 36 37 39 39 40 40 41 42 42 43 44 44 44 44 45 46 46 47 47 49 49 50 51 51 52 53

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

6 Exporting and Importing Data 6.1 Saving and reading of Matlab data . . . . . . . . 6.2 Export and Import of ASCII Data . . . . . . . . . 6.2.1 Writing ASCII data to a ﬁle . . . . . . . . . 6.2.2 Reading from keyboard . . . . . . . . . . . 6.2.3 Reading from a ﬁle . . . . . . . . . . . . . . 6.3 Importing and Exporting Data from/to Databases 6.4 A detailed example . . . . . . . . . . . . . . . . . . 6.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . 7 Graphic 7.1 Overview . . . . . . . . . . . . 7.2 The plot command . . . . . . . 7.2.1 plot with one argument 7.2.2 The plot command using 7.3 Movies . . . . . . . . . . . . . . 7.4 Images . . . . . . . . . . . . . . 7.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . two arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8 Numerical linear algebra tools 8.1 Full matrices . . . . . . . . . . . . . . . . . 8.1.1 Deﬁning matrices . . . . . . . . . . . 8.1.2 Calculating with matrices . . . . . . 8.1.3 Matrix decompositions . . . . . . . . 8.2 Sparse matrices . . . . . . . . . . . . . . . . 8.2.1 Constructing sparse matrices . . . . 8.2.2 Iterative methods for linear systems 8.3 Exercises . . . . . . . . . . . . . . . . . . . 9 Numerical Methods 9.1 Polynomials . . . . . . . . . . . 9.2 Quadrature . . . . . . . . . . . 9.3 Probability . . . . . . . . . . . 9.4 Other functions . . . . . . . . . 9.5 Ordinary diﬀerential equations 9.6 Partial diﬀerential equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

CONTENTS 9.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3 53 55 55

10 Examples 10.1 Random number generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Chapter 1

Introduction
1.1 General Remarks

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

1.1.1

What is Matlab

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

1.1.2

Why might Matlab be useful

• In industry Matlab is a standard tool for solving mathematical problems numerically. • Mathematical codes might be written in C or Fortran. Nevertheless, mathematical software development is largely done using Matlab. • There are several toolboxes around to solve advanced and complicated problems. • The linkage of Matlab and Simulink (also from MathWorks) provides engineers with mathematical 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

In case we need one of these windows we can get them easily from the pull down menu ”windows”. . However when problems are more complex we will see later how we can write scripts and functions. actually it makes sense to create several directories and subdirectories to work with Matlab. In the command window you will ﬁnd the Matlab prompt > > Many little problems can be easily solved directly from the prompt. But we start with the Matlab prompt. as the online help function is extremely helpful. Matlab was originally designed for Numerical Linear Algebra and its Applications and has grown now into Numerical programming and its Applications. it is not designed to do analytical or axiomatic calculations. Starting the Matlab development center one usually gets several windows. This command window and the Matlab editor will be the main tools. the remaining windows can be deleted without any worry. Otherwise the command ”help” will be one of the most frequently used commands. The probably most important command at least when working with the Matlab shell is the ”exit”-command. specially for Functional Analysis gap Computer Algebra System for experts. Many of them are specialized for a speciﬁc area of mathematics. The following lest of mathematical packages and libraries is not exhaustive and for example many more numerical libraries can be found on ”www. one of which is the command window. INTRODUCTION • precise error messages • high quality math routines • freely available source codes for many functions • large variety of easy to use graphic tools • memory eﬃcient data representations and routines which exploit sparsity 5 There are many other mathematical software packages which are brilliant for their special applications. as one creates various ﬁles containing data or Matlab-functions. Matlab can be started from any directory. maple Computer Algebra System.CHAPTER 1.2 First Steps From the Unix/Linux command line one can start Matlab simply by typing matlab to get the development center or matlab -nojvm to get the Matlab shell.org”. Matlab is no exception. specially in Algebra femlab Finite Element Software Packet for numerical approximations of Partial Diﬀerential Equations 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.netlib.

As done above we will present Matlab-code as it should be typed in on the command line. INTRODUCTION 6 1. Now as the demos have opened up please have a go at them. for the ”luinc” function which calculates an incomplete LU-factorisation. To start working with Matlab type > demo > > > followed by the [Return]-key (Matlab starts to perform only after the return key has been pressed).1 Demo To get started Matlab provides several demos demonstrating how Matlab works ranging from introductory material on datatypes up to solving partial diﬀerential equations. 1. Getting started: Rudra Pratap Getting Started with Matlab (Oxford) Duane Hanselman & Bruce Littleﬁeld Mastering Matlab (Prentice Hall) Starting. and ”type GMRES” diﬀer greatly. however in case you like to have an additional source these are recommendable books. In some cases we will also illustrate the resulting eﬀect but mainly we leave this to the user to explore. so ”type luinc”. the ”help” command is very useful.2 Help > help > > > As noted. To get the corresponding help simply type > help luinc > > > Further one can get the source code of many such function by typing > type GMRES > > > However. 1. for example.2. For the core build-in functions the command ”type” will not work. With 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. Hence we do not suggest to buy one of the following books. but generally more advanced: . This course together with the online help should provide a good start for working with Matlab.3 Literature There are several books for getting started with Matlab or programming with Matlab and specially many books on how to use additional packages. there are build-in functions and further functions.2.CHAPTER 1.

2 Please type the commands ”help” and ”help ops”.CHAPTER 1.5 The purpose of this exercise is to show how easily mathematical problems can be solved in Matlab. Aufgabe 1.) Aufgabe 1. > > > > > > > > > > f=@(t. which should foster the understanding of Matlab.1)-cos(t)) (The last line plots the error between the numerical approximation and the exact solution. [t. Aufgabe 1. 1. INTRODUCTION Desmond Higham & Nicholas Higham Matlab guide (SIAM) Darren Redfern & Colin Campbell The Matlab Handbook (Springer) 7 The Matlab guide on how to use the graphic tools is also recommended. clear all windows but the command window and type the command ”help help”. The following code forces Matlab to provide a numerical solution to our initial value problem and plots the solution.x] = ode45(f. which you can activate by calling ”demos” and opening the section Other Demos or simply by typing ”travel”.0]*x. However in Chapter 7 we discuss the most import points. as there are so many graphical commands that we can not cover them all. What is the eﬀect of ”help travel” and ”type travel”? Aufgabe 1.) .x(:. plot(t. (Here you ﬁnd a summary of all the Matlab math operators.-1.4 Please test the ”Traveling Salesman” demo.[1. 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. area=pi*r 2 area area = @(r) pi*r 2 area(2) area(3) Why does the second command cause an error? What is the eﬀect of the command ”clear”? Aufgabe 1.1.3 Please try the following sequence of commands > > > > > > > > > > > > > > > > > > clear area= pi*r r=2. and specially not all their options.0]).x) [0.x(:.1 Start a Matlab-session.[0:0.1:10].4 Exercise In each chapter we provide a couple of exercises.1)) plot(t.

size and content according to the right hand side. the remaining three basic datatypes will be discussed in Chapter ??.1 Basics The basic datatypes in Matlab are matrix. The reason for the later is based in the automatic datatype conversion and the automatic memory allocation. 8 . string. However if you like to learn more about other datatypes type ”help datatypes”. Matlab itself distincts between small and capital letters. cell. struct. If you like to mark the end of a command but like to see the result you can use the comma or the [Return]-key. and .) .1 Deﬁnitions of numbers. > > a > > > Lets start with two simple lines Throughout this script we use the above form to highlight Matlab-code as written to the command line. (The comparison operator for equality is ”= =”. size and content are lost. = Assignment: With assigning a value to a variable all previous information of this variable such as datatype.Chapter 2 Numbers and Matrices 2. Here we consider just matrices. Matlab has a variety of further datatypes however they are neither essential nor are they needed explicitly in standard applications. The new variable a has now the type. vectors and matrices numbers > a = 1. 2. a Variable names: Here a is a name of a user deﬁned variable.2 2. In case you like to write more than one command into one line you need to use either the comma or the semicolon to separate the commands. Variable names start with a letter and may contain numbers and the underscore. however if your system does not some internal Matlab variables and functions might not be case sensitive.2. End of a command: The semicolon at the end of a command ﬁrst of all marks the end of the command and secondly suppresses the result.

The size of the matrix is given by the use of comma and semicolon. As one can see from above there are several ways to deﬁne complex numbers. > A > ans = 1 4 7 10 > > 2 5 8 11 3 6 9 12 . 2.9.2. ”j” and ”1i” are all the same number.11. Only the last form is recommended as the ﬁrst two forms are contents dependent. rationals.8. Changing the output format has now eﬀect on the internal working accuracy.2 i clear i i The output format depends on the values and a general output format. Integer. As above the deﬁnition has to be row wise not column wise. b= 2. so ”i”. So > > > > > > > > > > > > > > > > a=1 b = 1/3 c = 1.5e-3 are all of type matrix. however the result is likely to be N aN .10. The standard output format is short. For more on the output format see ”help format”.2.6. > > > [ ] Square brackets: Matrices are deﬁned by a pair of square brackets.4.2e2 d = 1+1i 2+i 3+j 1. so that one can do calculations with inf and N aN .7. as the following example shows > > > > > > > > > > > > > > clear i i=1. c=3.3. the imaginary unit. The comma is used to separate two columns and the semicolon to separate two rows. Further the two values N aN (not a number) and inf (inﬁnity) are treated as special numbers. NUMBERS AND MATRICES > a = 1.5. reals and complex numbers are all numbers and hence of type matrix. d=4 > > > 9 The datatype matrix encloses numbers and arrays of numbers.12].2 Matrices > A = [1.CHAPTER 2. The semicolon within the square brackets has a diﬀerent meaning than the semicolon at the end of a command.

.3)=12. > A=[[1.. > > A(4. Continuation points: The triple dot allows to continue a command on the next line.3)=6.6...12]].4] > > B = [1.. > > A(3.3)=3.CHAPTER 2.11. > > A(2. > 4. In the following we consider a few of them.5]. > > > The command ”A= [ ]” deﬁnes an empty matrix.4..5.9].10].3.[3.2)=8.9.. > > A(1.4.7. Some more variants to deﬁne the same matrix > clear > > A=[[1.8.12]. > > A(3. NUMBERS AND MATRICES 10 As all values in the matrix are integers the matrix is presented as a matrix of integer.12]. > size(A) > > size([ ]) > > > .[2. > > . > > A(2.. > > A=[A.3.. > A = [1.6].8.1.9. > > A=[A.5.1.6].11.12]].2. > > A=[A. > > A(1.10.[3. > > A(4.2)=5. This can be used to help with extremely long expressions and to improve the readability of the command.6.7. 10.1)=4. > > A=[A. In general the matrix is presented as a matrix of that class of numbers which contains all numbers presented in the matrix and where there is at least on matrix entry of this class.4] > > > As matrices are the main object to deal with in Matlab there are plenty of further possibilities to deﬁne them.2)=2.2. > > clear > > A=[].1i. > > A(3.3]..1)=1. > [7. > > A(2.1)=10.1)=7.5..10].8..3)=9.1. An empty matrix is of size 0 × 0. > A=[1.[8.3. 7..2)=11.9. > > clear > > A(1.4.2. > > A(4..11.11].

1 Matrix versus vector As the computer memory is accessed as a one dimensional array Matlab provides us to access matrix entries by a single index. we need the corresponding single indices which are provided by the function ”sub2ind”.3).3 Working with matrices > a=A(2.3]. which can be used as an index vector.3 Vectors > > > > > > > > > > > > a=[1. > > f=A(sub2ind(size(A).3]. > > J=[2. . If a and b are positive integers. 2. > > > 2. Column vectors are n × 1 matrices. a + 2.3).3.I. c=1.1) and (3.2). > > B = A(1:3.05]. a + b.3].2. . > > > We can easily access a single entry of a matrix my calling An entire vector and a submatrix can be accessed in similar fashion > b = A(:.4.3]. a + 3b. a + 2b.1. d=[1:5]. .2:3). b=[1. [1:12] A(:) = [1:12] A(5:9) In order to access a list of matrix elements simultaneously. The opposite action is given by ”ind2sub”. a : b.1.4). NUMBERS AND MATRICES 11 2. > I=[1.2). The command ”a:b:c” provides the numbers a. > > > Similar to accessing multiple entries of a matrix we can also change multiple entries of a matrix simultaneously . a + 1. . (2.2). is an eﬃcient way to get the numbers a.4). . . similarly for row vectors : Colon: The colon operator. > > > > > > > > > > A = zeros(3. say (1.2.J)).2. e=[2:-0.CHAPTER 2. than a : b is an integer valued vector. .2. (1. a + kb with k being the largest integer not larger than (c − a)/b. . a + k. > > b = A(1:3.1:1. Matlab allows B to be negative. with k being the largest integer such that a + k is smaller equal to b.

4. > > A(3. Matlab interprets each line before it evaluates it.2 Binary Operators In case of binary operations we need to take care of the dimensions of the matrices in use. 12] B=A C = A. a = [1 : 4]. the blas routines used within Matlab allow fast actions of of vectorized expressions.Negation: ”B=−A” provides the negative of A. 2. while binary operators connect two matrices in a mathematical way.4. Examples > > > > > > > > > > > > > > > > A = [1. f =a∗a .J)) = -2 > > > 12 Simultaneous actions are much faster than their corresponding sequential ones. 9. 8. and the simultaneous statement needs only one interpretation. 11. > > A(sub2ind([3. Matlab will post an error immediately. 5. A(1. Transposition: ”B = A.I. Transposition and complex conjugation: ”B=A ” assigns the transpose and complex conjugate of A. First we take a look at the standard actions for matrices with matching dimensions > > > > > > > > > > > > > > > > B = A + A. 6.CHAPTER 2. D = B − A. First. . 1) element. is mathematically correct for real matrices. In case of mismatch of dimensions. NUMBERS AND MATRICES > A(4. E = a ∗ a. however the matrices D and E diﬀer in their (1.4. 10.4]. often the use of helps to get the same code working for real and complex matrices!) 2. 2. ” assigns the transpose of A. 7. Second. C = A ∗ A. (While the use of .1 Unitary Operations There are three unitary operators .2) = -1. 2. 3. This is due to two eﬀects. F=−A The matrices B and C are identical. 1) = 1 + 2i D=A E = A. Unitary operators act only on one matrix. G=C 2 .1) = 0.4 Matrix Operation Here we distinct (a bit artiﬁcially) between unitary and binary operators.

3. . . > > % 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.9. . NUMBERS AND MATRICES Further we can multiply a matrix by a scalar and divide a matrix by a scalar > b=2. ... of b. commends can be started anytime in a line > > % and they run until the end of line. · 10−16 Some important constants . 2../A > > C=A. In this case the action is element wise > B = A. > 4.11]. Consider the linear equation Ax = b where A and b are known and x shall be calculated > b = [1 : 4] > > c = [1 : 4]. > > A = [1. Matlab knows further matrix operators which interpret the matrix as an array of numbers.9. beforehand we consider a few already deﬁned constants. 2.22 . .7. 2. . otherwise the entries are inf and a warning is stated.7182... rows respectively. vectors or matrices as arguments. so b is allowed to be a matrix!!) 2. However. > > y = c/A. which are then applied to all columns.5. > > c=b*A > > d=A/b > > > 13 however b must diﬀer from 0 for the division.CHAPTER 2. > > % This is a comment line.10. 2 > > B=A... Functions and Constants Most Matlab functions can be called with numbers.5 Matrices. 4.1415. 10.7.1 Constants Name π e machine precession Command pi exp(1) eps Value 3. 2. Matlab provides the solution operators ”\” and ”/” for the linear equations Ax = b and xA = b.6.10.. We now present a small selection of functions which can be called with matrices of any kind as argument. 7.*A > > > Further. .5. > x = A \ b.

NUMBERS AND MATRICES 14 2.4 Further Matrix Operation f liplr rot90 ipermute column permutation rotation of a matrix Inverse of ”permute” f lipud permute reshape row permutation permutation of the coordinate system general change of shape These commands change the shape and ordering of the elements of a matrix. following functions work in rand and the next ones work in 360 degrees sind asind cosd acosd tand atand cotd acotd For large arguments it is sensible to work in degrees as then the numerical evaluation is more precise.) . The following function interpret a given matrix as an array and applies the function element wise exp(a) log2(a) real(a) abs(a) exponential function logarithm with base 2 real part modulus log(a) log10(a) imag(a) sign(a) natural logarithm logarithm with base 10 imaginary part sign function.3*10 12 sin(e3e12*pi) sind(3e12*180) 2.CHAPTER 2.5.2 Trigonometric Functions sin asin sinh asinh cos acos cosh acosh tan atan tanh atanh cot acot coth acoth Matlab uses two sets of trigonometric functions. as indicated by the following example > > > > > > > > > > sin(pi) 3e12 .p)” needs to be p equal to either 1. (The commands ”permute” and ”permute” are not the standard math permutations but they permute the coordinates. 2. more numerical functions will be discussed in Chapters 8 and 9. p) p-(matrix-/vector-)norm The command ”norm(A.5. inf or f ro . direction In contrast to the previously noted functions the following ones interpret the given argument either as a vector or as a matrix norm(a) 2-(matrix-/vector-)norm norm(a.5.3 Some standard functions Here we present only a few standard function. 2.

2.7 Design a 10 × 5 and a 12 × 6 matrix with random elements. (You may use the ”plot(x. What is the eﬀect of ”b = diag(A)” and ”B = diag(b)”.  1  1 Aufgabe 2.1 Please work through the Section 2. .6 Deﬁne 3 × 4 a matrix with all entries zero and one with all entries equaling one by applying the Matlab-functions ”zeros” and ”ones”.4 Evaluate the solution  1  2   1 0   1  1   .sin(x))”command.3 What does √ 17−5 e3 −5 equal? of the linear system  2 1 0 3 2 1  x = 2 4 2  1 2 3 Aufgabe 2. . 4. Aufgabe 2.5 Plot the sine-function for the values between 0 and 2π. . Aufgabe 2. 12]. 3. Aufgabe 2.6 Exercises Aufgabe 2.8 Given our standard matrix A = [1. ..4 and make sense of the answers Matlab provides. To get a third matrix take the ﬁrst 25 elements of the ﬁrst and the last 15 elements of the last such that the third matrix has in its last entries those from the ﬁrst. NUMBERS AND MATRICES 15 2. . Control the size of these matrices with the command ”size”.1 to 2.CHAPTER 2.2 Calculate the quotients 1 + 3i and 1 − 2i. Aufgabe 2.) Aufgabe 2. The third matrix shell have the format 5 × 8.

for example vi. Additionally one can use the command line > edit > > > or respectively > edit name > > > The latter action opens the editor with the ﬁle ”name”.m to show that this is an ”M-ﬁle” to be used within Matlab. Hence they need an interface to get input data and to place the results. 4. we just enter the following to the editor 16 . In contrast a script works on the global data. Functions work only on local variables. The advantage of functions is that they leave the variables in the workspace unchanged. so all previously deﬁned variable are accessible (can be assessed. the disadvantage is they need more memory as variables transfered to the functions are implicitly copied. name needs to end on . pico and emacs under Unix and Linux or notepad under Windows. Additionally they allow debugging. 5.Chapter 3 Script and Function Files 3. 6] Starting with a simple example for a script. deleted) and are afterwards available in the form the script has left them. 3. The situation with scripts is the opposite.3 A ﬁrst script 1 2 3 4 display( A ﬁrst Script ).2 Editor In case the editor is not open it can be opened using the File-menu (”File→New→ M-ﬁle” or ”File→open”). The essential diﬀerence between scripts and functions is their eﬀect on the variables in the workspace (that are all currently deﬁned variables). that are variables deﬁned within the functions. 3. 3. 2. Of course one can use alternative editors. changed. However.1 General Scripts and functions are used to reuse larger program sections. clear who A = [1.

In order to allow a variable parameter length. starting with a letter followed up by any combination of letters.x] = plotsin(n). Then the variables nargin and nargout are deﬁned and contain the number of variables the user passed on to the function or respectively required as a return. ” ”. Any of the two list might be empty. independent of the number of elements. Basically the function declaration consists of ﬁve parts. the position within the in-list and out-list are important. then the name of the variable is enough. however with respect to the function name this is somewhat problematic. the last element in the in-list needs to be varargin and varargout respectively for the out-list. the name of the ﬁle is what matters! function Deﬁnition of a function: The Matlab command ”function” in line 8 deﬁnes this ﬁle as a Matlab function. here plotsin. As the names are allowed to diﬀer to their use outside. plot(x.1:3]. 3. The name of the function follows the convention for the names of variables. The name of the variables being used in the function deﬁnition and the code might diﬀer from the name being used in the help area. second the output list. > . x = [0 : 2 ∗ pi/n : 2 ∗ pi].y). fourth the name of the function and ﬁfth the input list of variables. ﬁrst the function command. Variable parameter Matlab allows the use of variable input and output parameter lists. 2-3 > > q(3) > > x=[-3:0. function out-list = f-name (in-list) As noted above the name of the function is for a single function in a function ﬁle not important. numbers and the underscore. we can use the ”@” command or we could use the ”inline” command > q=@(x)x. Parameter lists Input and output lists: If the out-list consists of a single variable. for example see lu. Notation Capital letters: In order to better distinct between variable names and standard text within the help statements (leading comment lines) one usually writes the name of the function and the variable names with capitals. Otherwise the out-list needs to be enclosed by a pair of square brackets. 19 Saving this as plotsin. ”plotsin(5)” and ”plotsin(100)”. as the name of the Matlab function is case sensitive. A short but meaning full name helps understanding your code. ﬁrst we could write an M-ﬁle.m we can now call ”help plotsin”. y = sin(x). With respect to the variable names this is ﬁne.6 Inline-Functions There are three ways to deﬁne simple math functions. third the assignment sign (=). Actually man build-in function react diﬀerently depending on the number of parameters passed to the function. and asked as a return. Further note that the name of the function as written within the ﬁle is unimportant. SCRIPT AND FUNCTION FILES 8 9 10 11 12 function [y. then the function does not require any input variables and it certainly does not return any value.m. however this might upset people checking your code. What matters for Matlab is the name of the ﬁle.CHAPTER 3. The in-list requires always round brackets. for example see plot.

x. plot(X.Y. We can also pass on functions as an argument.y). however if initial is a set of two values. Here the parameter list consist out of those variables one likes to pass on and the formula is a math formula as it could be written to the Matlab prompt. satisﬁes f (a) ∗ f (b) < 0.6.b) X = [a:(b-a)/100:b]. we can provide the name of a function and then call the function inside the ﬁle using the ”feval” command.B] and % approximates the minimum in [A.q(pi) 20 @ Function deﬁnition: The command ”@(parameter list) formula” provides an easy way to deﬁne simple functions.A. hold on plot(a.’r*’).0) p(pi) .ind] = min(Y). In case initial is a scalar.Y.Y] = approx min(F. SCRIPT AND FUNCTION FILES > > > > > > > > > > > > > > > > > > > > y=q(x).B]. % function [x. 3.y] = approx min(fct. x = X(ind). b] then fzero requires that the function.3) q(fzero(q.a.3)) plot(x.1 Subfunctions Within one M-ﬁle we can deﬁne several functions. [y. fzero Finding zeros of a nonlinear function: The command ”fzero(function.initial)” tries to detect a value X for which the function is zero.CHAPTER 3. however from outside we can call only the ﬁrst one. (The ”@” command is not available on all machines and platforms) inline Function deﬁnition: There are several ways to deﬁne an inline function using the command ”inline”. the others are only accessible from inside this M-ﬁle. hold Freezing current plots: The command ”hold on” freezes the current plots. . Y = feval(fct. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 % [X. More elegant is to pass on the function itself. the function starts from this value. hold oﬀ p = inline( x. To reverse the freezing type ”hold oﬀ” or simply clear the graphic window with ”clf”. see ”help inline”. present result(X.B) % plots the function F in the interval [A.x.y).z). say initial = [a.Y. In this case fzero will always succeed and determine a value x.0. fzero(q. 2-3 . − ). so that the following plotting commands are added to the current one. First. Here the inline functions are quite useful. say f (x).X). return %%% function [ ]=present result(X. This can be achieved in two ways.

6. What happens now if you type ”cd” in the command window? Next type ”cd=1” and ”who”. The command window has the standard functionality. ∗g ). say ”fprintf(’Hello world’)”.m”) . and can do some manipulations with them. 17 plot(x. The execution of a script ﬁle can be started directly from the editor window.pi) > > > where q is the inline function ”q = @(x) x. Which use has the ”cd” command? Write a small script. 3. we can add and delete break points as well.m” by ”!del cd. 2-3”. what is the eﬀect of these two commands? (In case of a Windows machine exchange ”!rm cd.) Saving above code as Amin. Aufgabe 3. Here Matlab provides a wonderful environment for debugging.7 Debugging Standardly when programming one makes mistakes in the code and ﬁnding them afterwards can be a tantalizing task. that are points where Matlab stops the execution of a ﬁle. What happens now if you type ”cd” in the command window? Now type ”clear cd” and ”!rm cd.CHAPTER 3. SCRIPT AND FUNCTION FILES 16 hold on. while a function ﬁle needs to be started from the command line. Aufgabe 3. 3. 18 21 (The last argument in the ”plot” command forces Matlab to use green stars for this set of data.-2. Another click and it is cleared.m”. By doing so Matlab sets a red point in front of this line to indicate that a break point is set. can be done by pressing the left mouse button on the corresponding line number in the editor window.1π].3 Clear all current variables in the workspace using ”clear”. The debugger is part of the editor window. This implies that we can view the values of all current variables.2 Implement the example from Section 3.z.8 Exercises Aufgabe 3. see the debug menu.1 Write a script for plotting the tangent and the hyperbolic cosine within one coordinate system for the interval [−π/4. From the ﬁrst break point on we can decide to go step wise or continue till the next break point. however the current data available are those form the debugger.m we can type > Amin(q. Once a break point is reached the Matlab prompt in the command window chances to indicate that the debugger stopped at a break point.1 and deﬁne a break point and execute the ﬁle step by step. and save it as ”cd.m”. Setting of break points. 0.

Following the if command and the conditional statement.1 Branching Matlab has two branching commands.1. however care must be taken on their ordering. As the block of 1 2 3 4 5 if (condition) commands {elseif (conditions) commands } [else commands] end can be viewed as command in itself. else fprintf(’Where is a?\ n’). Further we consider here the command ”ﬁnd” which occasionally can be used instead of ”if” and ”switch” statements. 4 22 . so we can employ an if statement within another one. ifelse and else can be followed by any number of Matlab commands and ends with the next elseif. 2 3 else if (a>-3 & a<-1) fprintf(’a is between -3 and 1\ n’). 4. Any sub-block started by if. there can be as many Matlab commands as the user wishes until the ”end” command which ﬁnishes the if statement.Chapter 4 Conditional Statements 4. Finally there might be one ”else” command. else or end statement.1 1 2 3 4 5 6 7 8 Branching with if if (a>1) fprintf(’a is larger than 1\ n’). The block might have several ”elseif (condition)” statements as the user likes. elseif (a>-3 & a<-1) fprintf(’a is between -3 and -1\ n’). 1 if (a>1) fprintf(’a is larger than 1\ n’). ”if” and ”switch”. end The ”if” command is followed up by a conditional statement enclosed in round brackets.

B.1. b) not a a and b a or b a and b a and not b or b and not a Additionally there are the operations ”a&&b” and ”a||b”.1.B. b) xor(a. 4 fprintf(’Variable B is of tye matrix and has the value 1’). For example if a variable can have several diﬀerent values (limited in number) then for each value a diﬀerent branch can be selected. The shifts being used in above manner have been placed to indicate the logical structure.B)] For mathematical comparisons we have the operations > >= == larger larger equal equal < <= ∼= smaller smaller equal not equal 4. A condition is a boolean expression.B).CHAPTER 4. Further these operations can be applied to matrices a and b where a and b need to have matching size.A&B] [A. any other value is considered as being true. 3 case 1. 2 fprintf(’Variable B is of tye string and has the value %c’.2 Branching with switch The ”switch” command allows to branch into multiple branches.xor(A. B=[0. similarly for a true in the ”a||b” condition.A|B] [A. similarly for ”a|b” and ”a||b”. then b is not evaluated in the ”a&&b” condition. The ﬁrst example uses one (extended) block while the second one uses two (simple ones).3}.0.1]. In Matlab the value for false is ”0”. So if a is false. In case of ”a&b” and ”a|b” both expressions a and b are evaluated before the logical expression & or | is evaluated. an inner and outer statement. For a better understanding of the boolean operation check the following results > > > > > > > > > > > > > > A=[0. [A. However in contrast to other languages Matlab allows to group several cases as one branch. While both programs provide the same result they diﬀer with respect to their number of if blocks. the statement is either true or false.1.A| ∼B] [A. 1 switch(B) case ’a’.B.0. The logical meaning is the same for ”a&b” as for ”a&&b”. 6 .1].B. that is. 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. The following boolean operations are provided ∼a a&b a|b and(a. 5 case {2. CONDITIONAL STATEMENTS else 5 6 end 7 end 8 9 23 fprintf(’Is a nowhere?\ n’).

k) 4.3 Searching with ﬁnd Often we need to check components of a matrix or vector or even just to change a few of them according to some indicator. but we do not know any more’). ﬁnd Vectorized query: ”ﬁnd(condition)” returns the indices of the vector/matrix for which the condition vector/matrix has the value true. stop=2*pi.B). end. 9 end 10 11 24 4. CONDITIONAL STATEMENTS fprintf(’Variable B is of tye matrix and has the value %d’. As Matlab ﬁrst evaluates the vector for which the loop need to be run. negative increments. that is a value diﬀerent from zero. 4. In order to break up. Actually vectorizing Matlab commands leads to much better (faster) performances than using loops instead.2. that is all values for i = [2 : 10]. 7 otherwise 8 fprintf(’Variable B is deﬁned. 2 3 end. Often loops can be avoided by vectorizing the command.1 The ﬁxed loop for This type of command is useful if a ﬁxed number of cycles of the loop need to be performed.i). 5 The vectors b and c diﬀer only in their ﬁrst element.CHAPTER 4.2 Loops Here we have the ”for” and ”while” loops. it is also possible to use negative numbers. 4 c = [1 : 10] . and non integers for the variable i. for i = start : increment : stop fprintf(’i has now the value i = %f \n’.j] = ﬁnd(B<6) ind2sub(size(B). Nevertheless loops are still important. 1 2 3 4 5 6 7 start = -3. increment = 1. stop and restart the loops Matlab provides the commands ”break” ”continue” and ”return”.5. Matlab provides with the ”ﬁnd” command a very useful tool for this task. .1:4:10] ﬁnd(A<6) B=[1:10]’*[1:5] k=ﬁnd(B<6) [i.1:3:10.1. > > > > > > > > > > > > > > A=[1:2:10. A ﬁrst simple example for a for loop 1 f or i = 2 : 10 b(i) = i.

then the loop can be stopped from the command window by pressing the keys [Control] and [C] simultaneously. 2 while (j <= 20) for i=1:j 3 A(i.2 The conditional loops while The while command uses a boolean condition which is evaluated at the beginning of each cycle. 1 i = 0. Occasionally implementation is hampered with a mistake and a loop does not stop by itself.5) i = i+pi. here an upper right matrix is deﬁned 1 j=1. 3 if and(i<10*pi. In case the loop is enclosed in another or even several loops. ”continue” and ”return” can also be used within a for loop. especially in an inner loop if all loops should be stooped.i). 7 fprintf( i has now the value i = %f \n’.2. 11 12 end. continue step over. that is the condition has the value zero. only the inner most loop is stopped. 8 if (i>20*pi) % however here we stop the loop 9 break. 4 end 5 . Matlab goes back to the start of the loop and continues the loop with the next cycle. As this command aborts the execution of commands within an M-ﬁle the command should be preceded by commands ensuring that the output variables are set accordingly. 2 while (i<9. 1 i = 1.CHAPTER 4. 10 end. 13 break immediate stop of the loop This command stops the loop immediately. The commands ”break”. Another example for loops. CONDITIONAL STATEMENTS 25 4. 4 5 end.j) = i 2+j 2-(i*j). 5 continue 6 end. 3 fprintf(’i has now the value i = %f \n’. return exit M −f ile Strictly speaking this is not a loop command. 6 As every value diﬀerent from zero represents the boolean meaning true the following example presents and endless loop. continue: With this command the remaining commands in the loop are ignored.i). so the remaining commands in the loop are not executed and the loop condition is ignored. however it gets almost only used within a loop.i>pi) 4 fprintf(’We do nothing \n’). the loop stops if at the beginning of one cycle the condition is false. 2 while 1 % this makes the loop an endless one i = i+pi.

1)”.3 Exercises Aufgabe 4.34)”. ”euclid(4)” and ”euclid(4. which should return the largest common divisor of two input arguments. Test your function by calling ”Fibonacci(3)” and ”Fibonacci(41. Aufgabe 4. If the input value is not an integer an error message would be ﬁne. ”euclid(27.4 Write a function ”euclid”.2 Write a function ”Fibonacci”. Test your function by calling ”euclid(12.2)”. Aufgabe 4.1 Please carefully work through this section and execute the scripts.3 Write a function ”fact”. Test your function by calling ”fact(7)” and ”fact(9. CONDITIONAL STATEMENTS j = j+1.-3)”.1. This function has one input variable an returns all Fibonacci numbers up to the value of the input variable. Aufgabe 4.CHAPTER 4. This function has one input variable and in case the variable is a positive integer it shall return n!. If the input variables are non integers or not enough input arguments have been passed on to the function than an error message should be provided.8)”. 6 7 end 8 26 4. .

we can not see clearly whether the output from line two and three are numbers are numbers or not. ” ”. Hence the datatype and the context A previously had does not matter. numbers and other signs usually all known as char enclosed by single quotes. ”help datatypes”. for example ”’hello’”. actually they are not. struct and cell To get more information on other data types please use the help command.Chapter 5 Other data types Due to the automatic type conversion by Matlab we consider here only the four main data types. Some more examples for strings > > > > > > > > > > > > > > A = [3. > > > > > > > > > > C = 345 C(1) C(2) C(1) ∗ C(3) The output format is ambiguous. We already discussed the data type matrix in Chapter ??. we obtain a numerical value with C(1) ∗ C(3). 5. they are strings like C itself. Here we discuss the datatypes string. 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. so of type string. While C(1) and C(2) return the strings containing the speciﬁc numerical characters. 4] % this is a matrix A = hello world % now A is a string B = [ hello . Due to the automatic type conversion we do not need to allocate memory nor do we need to deﬁne string variables. Matlab allows easy access to strings and several ways to concatenate strings.1 Strings A string is a collection of letters. When concatenating two strings there is no additional sign in between the two strings. The opposite eﬀect occurs in 27 . With ”ischar(C(1))” we can check if C is a string. As multiplication is not a string operation but a matrix operation the two values C(1) and C(3) are interpreted as being of type matrix and there value is determined using the ASCII table.

type A. S=getﬁeld(S. A A. is part of the struct S.[1. matrix.[3. . The datatype cell is explained in Section 5.2. A.4..2].59.4. 5.2].6]. this variable can have any datatype. struct and cell. 5. ) creates a struct: See ”help struct” for speciﬁc information.content B=struct( type .name=wert”. content .[3.. Each cell element has a variable as content. Simply this can be used to construct and simultaneously name some components if not all of this newly formed variable and simultaneously initialize these components. The cells elements can diﬀer in datatype and size.[1.content=[1. > > > > > > > > > > > > > > > > > > > > > > > > > > A.6]).wert) Assigning: this is a more complicated form for ”S. name . name.1].4. isﬁeld(S. content . C=[struct( type . OTHER DATA TYPES > D = [ hello . ﬁeldnames(S) List of components: Returns a one dimensional cell of strings containing all component names.3. . however in case of programming with arbitrary and unknown options this is quite useful. string. and 41 are interpreted as characters getting the corresponding char again using the ASCII table.5. name ) components test: tests if a certain component.45. size . struct( type .type C Matlab supplies the following routines to work with the datatype struct struct(. name ) Remove component: Removes the speciﬁed component.2 Structs This datatype is frequently used by Matlab build-in functions. content .5. .3 Cells Cells can have several dimensions of independent length. matrix .2]. the result is an empty struct.[1. A. size .3. For these component names the standard name convention applies. Explicit type conversion is more readable than the implicit conversion. specially for advanced options. S=setﬁeld(S. size .6]).2.size=[3.CHAPTER 5.2. 45. C(2). matrix . The advantage of this datatype is it can carry various components which have their own name.0)]. thus the ordering of the information is unimportant. S=rmﬁeld(S.5.3.3..name”.type= matrix .41] > > > 28 Here the numbers 59. name ) Access: this is a more complicated form for ”S. Implicit type conversion is bad style!! The explicit operations are ”double(A)” and ”char(A)”. for example ”help luinc”. if it is the last component. matrix .content C(1).

we can do math manipulations or string operations if the datatype of the contents is matrix or string respectively.’hello’} A{2} A{5} A(5) A{4}(2.} Create cells: This is one way to deﬁne cells. 3. . [2. Two cells in a row are separated by a comma. .’What shell we say? } D = {A.4. . . so for example. OTHER DATA TYPES > > > > > > > > > > > > > > A = {1. . which can be achieved using the command ”unique”.4 Sets The datatype cell can be used for set operations. B) setxor(A. . C} D(3) D{3} D(2) D{2} D{2}{2} 5. [5. ) Create cells: ”cell([3. rows of cells are separated by semicolon as we are used from matrices. A(. 6. As the cell contents is a variable. 4. simply listing all the variables and data in curly brackets.’world’.A)” which evaluates if a is a member of A and returns the value 1 (true) if so otherwise the value 0 (false). 4].CHAPTER 5. hello } 29 {. we can not apply any math operation to A(1). [2. B) setdif f (A. {}. A draw back of this way of deﬁning cells is. B) intersect(A. 2. Let A and B be sets then the following operations are deﬁned maths expression A∪B A∩B A\B (A ∪ B)\(A ∩ B) Matlab command union(A. Keep in mind all rows need to have the same number of cells. 4. 8].} Assessing a cell: Matlab distincts between the cell element and its contents. A 4} C = {’hello’. Using the curly brackets we can assess the cell contents. 3]. cell(.2])” deﬁnes a three dimensional cell and set the element values as empty. 1) B = {1. > > > > > > > > > > > > > > > > > > > > A = [1. 3]. . therefore the cell needs to consist of elements with datatype string only. . B. B) Additionally there is the query function ”ismember(a. 7. Further each content is only allowed to appear once. B = {A. A 2. that we can only construct one and two dimensional cells. . A 3.) Assessing cell element: In contrast to the previous way of assessing a cell A(1) is still a cell. Some more examples for cells. A{.

D) fprintf( We have lost\n ).-pi.parameters) or fprintf(ﬁle. Here we present only a few of them. a. The syntax is given by fprintf(format. > fprintf( %f %e\n’. B). { 9 . A . 2. For writing interactive codes. read and write strings. The latter we discuss again in Section 6. the commands ”input” and ”fprintf” are useful. 1 value = input(’Please enter an integer \n’). > . for further information please see ”help strings” and ”help strfun”. However format might include formating information such as \t \n tabulator linebreak Further format can contain several place holders for writing some data in this places %d %f %e %s integer ﬂoat ﬂoat in exponential form string For each placeholder there should be a Parameter containing variables precisely of this format. An empty input is interpreted as a 0 × 0 matrix.-pi. 4. A.format. d} B={1. 4.CHAPTER 5. > > fprintf( %8. 3. 3 input Interactive statement: This command causes Matlab to wait until the user presses return and provides as a result what ever the user has entered. 4. b. 2. OTHER DATA TYPES > > > > > > > > > > > > A={1. 2 fprintf(’You entered %d \n\t Thanks \n’.value). c. 4. it has the same functionality as the ﬁrst just with the diﬀerence that it prints to an already opened ﬁle. format is enclosed by single quotes and any plain text contained in format is printed as such.parameters).4e\n’. fprintf formated printing: This function is almost identical to its counterparts in other programming languages.4f %8. 5. end > > 30 5.5 Working with strings There are many functions available under Matlab to modify. 5} B = unique(B) B = union(B. B }) if ismember( 3 . Often one likes to improve the printout by allowing only speciﬁc amount of places for each sort of data. however. 7 . 7 ) D = union(intersect(A.-pi).-pi).

D = is .-pi.E) u = strﬁnd(question.4. F = ﬁne .u(2)-1)) fprintf(’%s %s %s\n’.question(u(1)+1. B and C.7 Exercises Aufgabe 5. We have used fprintf and sprintf already in Section 3. E = life .E. d} and C = {c. Some useful function for working with strings strcat strcmp strﬁnd strtok concatenating strings comparing strings searching strings within strings splitting strings according to a list of token More functions to work with strings can be found by calling ”help strings” and ”help strfun”. celldisp(B) displays the cell content element wise to the screen. OTHER DATA TYPES > fprintf( %2.D. (For example when using cells as sets.6 Working with blocks We have already seen how to create cells and how to access cell elements and their contents. > > > > > > > > > > > > > > > > > > > > A = hello .F) end > > 5. {} and {b. C = How . .-pi.CHAPTER 5. b. > > fprintf( %+2. > > > 31 sprintf formated string: In principle this command works the same way as fprintf but it returns a string.’ ’) if strcmp(D.1f %2.-pi).-pi). c.1f %2.1 Enter the sets A = {a. B = world .) Creating cells cellplot(B) Plots the structure of the cell. Here we provide a few more commands on working with cells.) 5. d} using set operations applied to the set A. c}.1e\n’. and writes the content into the plot. d} and construct the sets {a}. .B) question = strcat(C. so the result can be passed on to a variable. greeting = strcat(A. (Only in modern versions) iscell(B) test if a variable is of type cell. ’ ’.1E\n’. cell(. ’ ’.D. then all the cell elements need to be strings. B = {b. iscellstr(B) tests if all cell elements are strings. ’ ’. .

OTHER DATA TYPES 32 Aufgabe 5. temperature (number) and rain (number). temperature 20 19 25 17 21 21 rain in ml 0 3 0 10 1 0 . Each struct has the components Place (string). The function shall print to the screen the weather information for each vector element in a nicely formated way. Deﬁne W eather with the following data place Koeln Duesseldorf Frankfurt Oﬀenbach Mainz Hanau and call ”Forecast(Weather)”. which works on the data Weather which is a vector of structs.CHAPTER 5.2 Write a function ”Forecast(Weather)”.

6.content2. b and C.1 = ’ and now? ’.4). say name.dat”. A(:) = [1:12].’unsorted Data ’. This is useful when writing to an apriory unknown ﬁle. so here saving the variables a. C ) > > > where name is now a string variable. B = struct(’what’. we can call To save only a collection of variables we can use > save name a b C > > > instead. storing them will eventually if not immediately ﬁll your disc. > > > > > > > > > > A = zeros(3. a . B.Chapter 6 Exporting and Importing Data Attention: Matlab is a nice toolbox to work with even in case of large sets of data. The opposite action of ”save” is ”load”. 33 .4)). B. Another way to call save is to use > save(name. Especially it is straight forward to create huge amounts of data.content1 = ’hallo world ’.cell(2. With > load name > > > we recover the data which we stored with the ”save” command. b .’content’. Matlab extends the name of the ﬁle automatically by ”.1 Saving and reading of Matlab data > save name > > > For saving all Matlab data in a ﬁle.

In case A the text document is written in L TEX then including a table is a bit laborious.mtx’. fclose(ﬁd).’%’). In the following A we present a function which automatically writes a ﬁle containing L TEX code for a table. > > A = spconvert(t(2:end. R = text. A = str2num(scanf(ﬁd. 6. which are either part of a toolbox or might be downloadable from the web. however there is no single tool which helps for all databases and worse they are all not an integral part of Matlab.:)). who A clear ﬁd=fopen(’pores 1.’%c’).’r’).4 A detailed example Often when documenting research result data tables are included within a text document. while (length(R)) [T.’r’). As an example data table we use A 3 17 3 Title B 4 -1 -4 C 7 5 2 a b c A The corresponding L TEX code has the form 1 2 3 4 5 6 7 8 \begin{tabular}{|l| ∗ {3}{c|}} \\ \hline & \multicolumn{3}{c|}{Title} \\ \hline & A & B & C \\ \hline a & 3 & 4 & 7 \\ b & 17 & -1 & 5 \\ c & 3 & -4 & 2 \\ \hline \end{tabular} .CHAPTER 6. For some databases there exist Matlab database tools.3 Importing and Exporting Data from/to Databases This is a common problem when analyzing data.R] = strtok(R.’%c’)). > > full(A) > > > 36 6. EXPORTING AND IMPORTING DATA > > > > > > > > > > > > > > > > > > > > > > ﬁd = fopen(’Daten3’. end > t = str2num(T). fclose(ﬁd). As an alternative one can try to write out the wanted data from the database in ASCII format and read them in as above described and vise versa for exporting the data. text = fscanf(ﬁd.

delimeter. end.data.j)).data) ﬁd = fopen(fn. All other lines have the form ﬁeldname content . [rows. Aufgabe 6. fprintf(ﬁd.column). The following code provides a simple solution to the problem 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 function [ ] = latextab(fn. if (ﬁd<3) fprintf(’ Could not open the ﬁle\n’).. As an example for the inﬁle one can use ﬁle ”tobesplitted” together with the delimeters ”{’hi’.mtx using the command ”load” and using the ”ﬁd=fopen . In case a diﬀerent number of data columns shall be tabled then this must be altered accordingly. splits the text into several lines according to some delimeters provided by the user and ﬁnally the function shall save the data in another ﬁle.content(i. which reads in a ﬁle..CHAPTER 6.columns] = size(data.3 Implement the function latextab and insert comments. for j = 1:columns fprintf(ﬁd. The variables inﬁle and outﬁle are strings containing the name of the corresponding ﬁles. fprintf(ﬁd. end. 6.’& %d ’. make sure you understand the commands and ideas being used in this chapter. end. return. for i = 1:rows fprintf(ﬁd.5 Exercises Aufgabe 6. EXPORTING AND IMPORTING DATA 37 Here the number 3 in rows one and two indicates that there are three data columns. The commend lines start with ”%” sign in the ﬁrst column.” sequence of commands as in above script.’%s ’.outﬁle) > > > .’proud’.2 Load the ﬁle pores 1.row title(i)). however the inﬁle might have comment lines which shall be ignored. delimeter is a cell with elements of type string.1 As importing data and analysing them is often an integral part of work.4 Write a function ”split”.tab).’w+’).’we’. specially for the interface description. These comments shall be accessible be ”help”. fprintf(ﬁd. for i = 1:columns fprintf(ﬁd. Aufgabe 6.’\\\\ \\hline \n’).’& %s\n’. Further create the correct input data in order to get the output for the example table. The function shall have the interface > split(inﬁle.’\n’). Aufgabe 6.data. Non of the delimeters (except newline) shall be present in the outﬁle.char(10)}”. end. \\begin {tabular}{| l| ∗ {%d}{c|}\\\\ \\hline \n’. What is the diﬀerence between text and pores 1? Aufgabe 6.col title(i)).data.5 Write a function ”ignore(inﬁle)” which reads in the inﬁle.

What is the number which corresponds to the char representing a line break on your machine?) . str2num and strtok are helpful. EXPORTING AND IMPORTING DATA 38 The function shall return a struct having the ﬁeldnames as speciﬁed by the ﬁle with the matching content. (Clues: strcmp. Test your function on the ﬁle tobeignored.CHAPTER 6.

hold Freezing of plots: Standardly any plot command deletes all old plots in the currently activated graphical window and then plots the new graph. for example dps for ps-ﬁles. ”plot” and ”plot3” respectively.2. Many of these commands act in a similar way. Calling ”ﬁgure(number)” then the corresponding window is activated and in case it did not exist before it is opened. dpsc for coloured ps-ﬁles. which we will illustrate using the ”plot” command in Section 7. hence we can present only a few of them here. 7. ﬁgure Activating a graphical window: Windows for graphical outputs are called ﬁgure plus a positive integer. which have all their own command.1 Overview graphs log scale graphs diagrams ”stem” graphs contours surfaces others plot semilogy bar stem contour surf waterfall line scatter plot3 semilogx stairs stem3 contourf surface ﬁll scatter3 Here we provide a short and incomplete overview of graphical commands. Matlab has several types of graphics available. for example for simple plots in two and three dimensions. All graphical commands act on the currently activated graphical window. deps and depsc for eps-ﬁles and djpeg for jpeg ﬁles. print Printing to ﬁle: With ”print -style name” the content of the currently activated graphical window is printed to the ﬁle name. the graph is frozen using the command ”hold on” and all following plot commands add their graphs to the same coordinate system. 39 . Here are several useful options possible. The ﬁlename is automatically extended by the correct ﬁle extension according to the format speciﬁed by style. In order to get several plots into one coordinate system.Chapter 7 Graphic As the graphic tools are one of the key features of Matlab there are a variety of commands dealing with ﬁgures. To reverse the freezing type ”hold oﬀ” or ”clf”. loglog pie contour3 surfc ﬁll3 plotmatrix pcolor mesh image spy Additionally there are plenty of commands to change the handling of the graphs or their windows. The format which is used for the graphical output can be chosen with style.

3. 2. x d .2.2 The plot command using two arguments > > > > > > > > > > x = [1. 5. So when plotting a function in Matlab we actually do not plot this function but we connect a set of values which lie on the exact graph. r+ ) Here we have two distinctive possibilities to call plot The ﬁrst two results are in principle the same usage. The colours are blue yellow magenta The line styles are straight line dashed line -dotted line dash dotted line : -. The command ”plot(data)” takes two consecutive elements from the vector data and draws a straight line between the two points represented by the two values and their indices. b y m red green black r g k and instead of lines we can get just plot at the data points stars circles squares For further possibilities see ”help plot”. If data is a matrix with n columns. 4. > x = [-5:1:5] > > f = @(x) 1. a vector or a matrix. the entries of the vector data against their indices. 12] plot(x. 12] > > plot(x) > > plot(sin(x)) > > > 41 In general data might be a number. GRAPHIC > x = [1. 3. We can ask plot to use a speciﬁc colour and line style to do the plotting. 4. 5. 7. 8. sin(x)) plot(x . 7.5) > > plot(f(x)) > > > While the function has a pole at x = 0. 10. * o s dots crosses diamonds . 10. 9./(x-0. 11. This leads to the fact that Matlab graphs do not always represent the plotted functions accurately. here we only demonstrate that the orientation of the matrices x and y does matter. 11. 2. sin(x )) plot(sin(x). 9. then n graphs are plotted within one coordinate system. 6.CHAPTER 7. 6. 7.5 the plot does not even indicate this. In contrast the second argument diﬀers in the third plot. In case data is a vector one graph is ploted. 8.

axis oﬀ. colormap(map). > > > > > > > > > > x = [-10:0. > > > However. 2*x.3]). for i=0:50 view([cos(i/25). getframe graphic to frame conversion: In order to construct a frame one has to plot and label the graph before it is stored as a frame. Both can be achieved using ”pause” and ”pause(time)”. so the entries in A are interpreted as indices to the current colour map. ﬁgure(2) image(ﬂoor(X*3)*20). GRAPHIC 42 7. In case repeat is a vector. movie will show this frame exactly as it has been constructed before calling getframe.z). y = [-10:0. > > > > > > > > > > > > > > clear. clf. > > > Another example for the many possibilities within Matlab: image Pixel map: Given a matrix A then ”image(A)” is interpreted as a pixel graph. surf(x. The remaining vectors are interpreted as indices to the frames. Now if repeat is a scalar.sin(i/20). The speed is measured in frames per second. then it represents how often the movie shall be repeated. to construct a proper movie or better a slide show we have the following commands. X = rand(20).4 Images > load gatlin. movie Runs a movie or slide show ”movie(slides. 7.3 Movies For presentations one occasionally likes to show a short movie. z = sin(y -1). pause(0. colormap Changes the current colour map: Colormap needs a n × 3 matrix deﬁning the colourcoding accordingly to the rgb (read-green-blue) scheme.3) end > fprintf( Could you spot the minimal point? \n ). If the movie shall present mathematical results we can easily construct this with Matlab. 2+y .speed)” shows a sequence of frames stored in slides. so the ﬁlm can be played in any order independent of the ordering of slides.0. the ﬁrst entry of repeat has the same meaning as in the scalar case.1:10].repeat.1:10]. . image(X). The function returns a handle to the frame.y. image(X*60).CHAPTER 7. Sometimes it is just enough to run a script but to stop at certain steps for some speciﬁed time or until the user allows to progress. 2*cos(x-3). 2-sin(y *x).

”stairs” and ”pie”.5 Exercises Aufgabe 7. Tryout the commands ”stem”. Aufgabe 7.1 Assume the one dimensional data A = [1. First you should show in a stab diagram how many percent each party achieved. Please make use of the ”text” command in order to label your plots.3 The island Neverland recently had an election and the following table provides the results. . 4. Aufgabe 7. ﬁrst try the winner is best result ever always second no chance one vote 244 2074 488 1586 110 1 Your task is now to provide graphs for this set of result illustrating the outcome of the election. GRAPHIC 43 7.CHAPTER 7.2 How does the surface of exp(cos(x)) ∗ sin(y) look like for x. Then the people like to know how many seats each party got. but attention this island has a 5 % limit. ”bar”. Add labels and a title to the graph. y ∈ [0. 10]. 1. saying parties who got less than 5% will not get any of the 72 seats. 12]. 7..

2 Calculating with matrices A+B A A 2 A\B A. 8. A*B A/B A.1. As there are too many such routines we only discuss a few here. 8.1 zeros eye randn Deﬁning matrices null matrix identity matrix random matrix. normal distributed companion matrix ones rand diag kron all ones random matrix.1 Full matrices We already discussed part of this in earlier chapters.1. 8.*B expm(A) sqrtm(A) norm max sort trace null addition transposition and complex conjugation power solves AX = B element wise multiplication matrix exponential function square root of a positive deﬁnite matrix matrix norm row/column maxima sorts row/column-wise trace of a matrix null space of a matrix A-B A. but to have a better reference we recall those here again together with some new functions. equally distributed diagonal matrix Kronecker product compan ”gallery” provides about 40 diﬀerent special matrices./B logm(A) inv(A) cond min sum det orth subtraction transposition multiplication solves XA = B element wise division matrix logarithm inverse of A condition number row/column minima row/column sum determinant orthonormal base 44 .Chapter 8 Numerical linear algebra tools Like the graphic commands the methods for solving numerical linear algebra problems is a key part of Matlab. like Wilkinson famous matrices.

To get all three matrices. 8. In order to solve least square problems one can use the ”lean” QR decomposition with ”[Q.P]=lu(A). ”diag” returns a vector containing the diagonal elements of A.1. To Update the QR decomposition there Matlab provides the commands ”qrinsert”. Further matrix functions are listed by ”help elfun”.U. Singular values are for example important in model reduction. in this case the Jordan decomposition (which is calculated by eig) can be unstable and a better tool is ”schur”. that is A = V ∗ D ∗ inv(V ). triu Triangle above diagonal: Returns a matrix which has the same entries above the diagonal as the original matrix but zeros along and below the diagonal. If the real n×m matrix A is non square ”[Q. the functions needs to be called as ”[L. diag Diagonal: Applied to a matrix.R]=qr(A. where Q is an orthogonal and R an upper right matrix. NUMERICAL LINEAR ALGEBRA TOOLS If A is square then ”expm(A)” is deﬁned as expm(A) = ∞ k=1 45 1 k A . schur Eigenvalue decomposition: In case of normal matrices it should be equivalent to ”eig”. decompositions or factorisation of a matrix. Golub and van Loan ”Matrix Computations” and Watkins ”Fundamentals of Matrix Computations”. chol Cholesky decomposition: This is a special case of the LU decompostion for symmetric positive deﬁnite matrices only. where span(Q) = span(A). lu LU-decomposition: The factorization is based on Gaussian elimination using row pivoting to construct matrices L.D] = eig(A)” returns also the eigenvectors V . A word of caution with respect to this tool if the matrix A is not normal.R]=qr(A)” returns a square n × n matrix Q thus spanning the entire Rn . > A=rand(5)+10*eye(5) > > eig(A) > > B = A+A > . ”qrdelete” and ”qrupdate”. U and P with LU = P A.3 Matrix decompositions One important task is to calculate so called normal forms. Hence it can make use of the structure to save memory and computation. qr QR-decomposition: This function returns the QR factorisation of a matrix.CHAPTER 8.U]=lu(A). Most of these methods are nicely explained in Demmel ”Applied numerical linear Algebra”. eig Eigenvalue decomposition: Calculates eigenvalues of a diagonalisable matrix. tril Triangle below diagonal: Returns a matrix which has the same entries below the diagonal as the original matrix but zeros along and above the diagonal. The Schur decomposition has the form A = Q ∗ R ∗ QT . If the user asks for ”[Z.0)”. ”help elmat” and ”help matfun”. we have expm(A) = exp(A). however for nonsymmetric matrices ”schur” is more stable. k! So only if A is a scalar or a diagonal matrix. here the eigenvalues are along the diagonal of D.” then Z = P T L. The ordering in D and V match.”. 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 decreasing order. ”[V. However when applied to a vector it constructs a matrix with the vector elements along its diagonal while the remaining matrix elements are zero.

. Calling ”A = spdiags(entries. If m and n are positive integer then ”sparse(m. x = b. > > 8.m)” and ”speye(n. F= C-V*E*V 46 With ”diag”.n)” returns a sparse matrix with m rows and n columns where all entries have the value zero. The format consists of three numbers (row. D = diag(diag(A)). speye Sparse identity matrix: The diﬀerence between ”eye(n. NUMERICAL LINEAR ALGEBRA TOOLS > > > > > > > > > > > > eig(B) C = sqrtm(B). The magnitude of the index value increases one by one starting with the main diagonal. Such a format is readily implemented in Matlab and most routines and calculation work with this format as with the full format. end. In order to allow a fast and easy way to deﬁne them one can specify which diagonals shall be set.where. ”tril” and ”triu” one can construct iterative methods for solving linear systems. y = A\b. Hence we need some further routines for sparse matrices. spdiags Sparse matrix with diagonal structure: Many sparse matrices have some kind of diagonal structure.m.norm(x-y)). but the leading ten eigenvalues might be desired. However a few methods need there special tools. The main diagonal has the value zero all diagonals above have a positive index and all below a negative.1).1 Constructing sparse matrices sparse Conversion to sparse matrix: ”sparse(A)” returns the original matrix A but in sparse format. > > > > > > > > > > > > > > b = rand(5.CHAPTER 8.m)” is their memory eﬃciency. Thus the variable just knows that it is a sparse matrix of this format and does not need to store any further information. [V.D] = eig(B).column. Now the matrix entries is interpreted as a collection of column vectors. this is not just based on the fact that the other methods could not be applied but that the actual problem to be solved shifts. fprintf(’error ||x − y||=%f \n’. L = tril(A). Methods such as the Jacobi iteration or the Gauss-Seidel iteration are easily constructed using these tools. U = triu(A). % exact solution for comparison for i = 1:10 x = D\((D-A)*x+b).2 Sparse matrices In many applications the arising matrices are large if not huge and have few entries often with some pattern. For example there is usually no need to calculate all eigenvalues of a million by million matrix.2. where each column is placed along the diagonal according to the entries in where. 8.value) for each nonzero entry in A.n)” constructs an m × n sparse matrix. E = diag(sqrt(diag(D))). For such matrices the use of a sparse matrix format is important as it saves memory and computation. The vector where contains indices to the diagonals.

(The command ”whos” provides memory information of the current variables. However.) . D = A-C. The method reduces the error in the operator norm.2. D = diag(diag(A)).1 Deﬁne a 200 × 200 Matrix A which has the value 2 along its main diagonal and the ﬁrst upper and lower diagonal entries equal to −1. C = sparse(B). 47 8. end > tol = norm(y-x) > > z = pcg(A.0. cgs Conjugate Gradient Squared: This is a generalisation of ”pcg” to matrices which are still symmetric but no longer positive deﬁnite. > > > > > > > > > > > > > > A = spdiags(ones(100.-1. > > > > > > > > > > > > A = spdiags(ones(100. In many situations iterative methods on their own do not work suﬃciently well and require some sort of preconditioning.tol).b.100. B = full(A). whos spy(C).1).2 Iterative methods for linear systems pcg Preconditioned Conjugate Gradient: One of the most popular method for solving linear systems when the matrix is a general sparse positive deﬁnite matrix.-1.5.100).1. > > tol = norm(y-z) > > > The upper list is extremely short.5. here the residual is minimized.[-20. minres Minimum Residual: Another method for symmetric linear systems.) For a better overview on Krylov methods for solving linear systems see the book by Youcef Saad.-1. for i = 1:20 x = D\((D-A)*x+b).-1].1)*[-1.-1].100.1)*[-1.20].3 Exercises Aufgabe 8.0.CHAPTER 8.1. NUMERICAL LINEAR ALGEBRA TOOLS In order to obtain a full matrix from a sparse we can use the command ”full”.20].-1. ”Iterative Methods for Sparse Linear Systems”. gmres Generalized Minimum Residual: Probably the most popular method for solving linear systems when the matrix is nonsymmetric. b = rand(100. The Matlab commands ”luinc” and ”cholinc” construct some popular preconditioners. besides Krylov methods there are many other iterative schemes for solving linear systems.100).-1. How much memory does this matrix require in sparse and in full format.[-20.-1. (This is not even the tip of the iceberg. 8. x = b. y = A \ b.

m and call ”leastsquare1” to construct the matrix A and the vector b.3 Given the least square problem min Ax − b 2 . (8.2) and b) by solving (8.0)” and then solve Rx = QT b. x (8.2 Consider the matrix from Exercise 8. Calculate the solution of above problem a) by solving (8. Calculate the Cholesky decomposition of this matrix? Can the Cholesky factor be stored in a more eﬃcient way? Is it possible to construct the Cholesky decomposition using ”cholinc”? What happens if you calculate the Cholesky decomposition of the same matrix but now of size 100000 × 100000? Aufgabe 8.R] = qr(A.3) Download leastsquare1.1.3). NUMERICAL LINEAR ALGEBRA TOOLS 48 Aufgabe 8.1) You might know that the linear system AT Ax = AT b (8. however a better way to calculate the solution is to construct the lean qr decomposition ”[Q.CHAPTER 8.2) has the same solution as the least square problem. Is there any diﬀerence in the solution? .

1 Polynomials The simplest class of functions are polynomials. polyﬁt Approximation with polynomials: For a given set of data points. this technique ﬁnds a set of polynomials. ”poly” is not the inverse of ”roots”! polyvalm Evaluation of a matrix polynomial: As the function ”polyval” works entry wise it is not a matrix operation in the mathematical sense. for which Matlab provides some special tools. ”spline(X.x)” returns p(y) for all entries y within x. roots Roots of a polynomial: This is the inverse function to ”poly” as it calculates the roots of the polynomial. of the tools already available within the Matlab core we only discuss a selection here.points)” does not return the coeﬃcients but returns the y-values for the splines evaluated at points. polyval Evaluation of polynomials: ”polyval(p. ”polyvalm” uses the matrix multiplication and thereby provides the correct result. 9. but instead of one polynomial matching at all data points.Y. however the result is a struct.) ”spline(X.Chapter 9 Numerical Methods In contrast to the methods from Numerical Linear Algebra many numerical methods are not part of the core routines. 49 .Y. spline Piecewise approximation: Also a polynomial ﬁtting technique.Y)” returns the coeﬃcients of piecewise cubic polynomials which interpolate the data and satisfy some smoothness properties. While ”roots” is the inverse of ”poly”. with the entry form = ’pp’. poly Conversion of roots to coeﬃcients: For a vector of (complex valued) roots a normalised polynomial is deﬁned where the ﬁrst entry corresponds to the highest order of the polynomial and its entry is set to one. However. which provide able tools for speciﬁc tasks. (In fact the result has the datatype piecewise polynomial. There exist a variety of toolboxes which we do not consider here. Here p needs to be the coeﬃcient vector such that the polynomial has the form n zij = k=0 pk (xij )k . The length of the returned vector is one more than the degree of the polynomial.N)” returns the coeﬃcients of the least square polynomial ﬁtting problem with degree not exceeding N . ”polyﬁt(X.

0. var Variance: Like ”mean” but now for the variance. > > > > > > > > > > a = [2. fminsearch Multidimensional search for a minimal point: ”fminsearch(fun. If start is a pair of values . The fast Fourier transformation is applied when calculating the convolution of two polynomials. NUMERICAL METHODS 51 triplequad Three dimensional quadrature: Works similar to ”quad” however now for three dimensional problems. ﬀt Fast Fourier transformation: ”ﬀt(a)” returns the Fourier transformed values of the vector a. c = conv(a.start)” searches for a local minimizer if the function has the form f un : Rn → R. otherwise the quadrature commands will fail! 9.6].3].1.10) > > > Note.4 Other functions fzero Root ﬁnding for nonlinear scalar functions: ”fzero(fun. zeros(n − length(a). > f = @(x) exp(-sqrt(x)).CHAPTER 9.*sin(x). say a and b.3. mean Mean value: Given a vector it calculates its mean.3 Probability rand Equally distributed random variables: ”rand(n)” returns a n × m matrix with entries equally distributed in [0. std Standard deviation: Similar to ”mean” but now the standard deviation. but now a Gaussian / normal distribution has been applied. where b = a(1 : n) if n < length(A) and b = [a.8) . median Median: Like ”mean” but now for the median. that the multiplication is pointwise. See Chapter 10 for a practical example. for which f un(a) ∗ f un(b) < 0 holds then fzero safely ﬁnds a zero. The classical problem of Fourier transformation is also solvable within Matlab which is quite handy for many applications. > > quad(f.b) af = ﬀt(a. Further when calling ”ﬀt(a. 1].n)” the result is the Fourier transformed of b.1. iﬀt Inverse fast Fourier transformation inverse of ”ﬀt”. randn Gaussian distributed random variables: Like ”rand”. 1)] otherwise. 9. cov Covariance: The entry must be a matrix and its columns represent diﬀerent experiments while its row represent the realizations of diﬀerent random variables. given a matrix it calculates the column means.start)” searches for a zero of the nonlinear function fun. b = [7.8) bf = ﬀt(b.

> > > > > > > > > > > > > > > > > > f = @(t. bvp4c Boundary value problem solver: ”bvp4c” is a fast and easy to use boundary value solver based on collocation. which are an important subclass of initial value problems. Another approach is to use collocation.X] = ode45(f.10].x) [-0. As an example the methods ”ode23s” and ”ode15s” are specialised tools for stiﬀ problems. Another standard problem with ODEs are boundary value problems such as uxx + (1 − u)(1 + u2 )3/2 x = 0 u(−1) = u(1) = 0.1.1 u u(0) = 1 0 (9.toc plot(T. interval = [0.start).0]. plot(T. A good guide to these tools is the book by Higham & Higham ”Matlab guide”. NUMERICAL METHODS > df = af.-1.interval. that are problems of the form du dt = f (t. . which are more robust but usually not that accurate.[T.1 1 −1 −0. u) u(0) = u0 for which Matlab provides the functions ode113 ode23s ode15i ode23t ode15s ode45 ode23 Above methods combine several numerical ideas to counter some of the intrinsic complications initial values problems often have.*cos(T).*bf > > d = iﬀt(df ) > > d = d(ﬁnd(d)) > > > 52 9.1) A numerical approximation (ignoring the exact solution) can be calculated using for example ”ode45”. (9.exp(-T/10).5 Ordinary diﬀerential equations A standard task in applied maths is to solve some initial value problems.-0.1. Further these methods can be ﬁne tuned using some optional parameters. start = [1. % As comparison hold on. Consider the problem u = ˙ which has the exact solution u(t) = e−t/10 cos(t) −sin(t) .X). r ). tic. This problem describes a drop of water.2) −0. One possibility to solve such problems is to use shooting methods which reduce this problem to a sequence of initial value problems to be solved.CHAPTER 9.1]*x.

grid. Additionally we need boundary conditions of the form pa (x. While few of these problems can be solved explicitly. say bound. . with values = initial(points). ub. u. of the form   pa  qa   bound(xa. ux ) Similar to the odes we need some initial conditions. Here c. t. t)F (x.) Finally we can call the Matlab solver for PDEs with ”pdepe(m. ux )  . the calculation is carried out! (More points leads to more work and higher accuracy. ux ) F (x. say initial. In order to work with ”pdepe” we need a function F with   c(x. t.bound. u. While tspan has little or no inﬂuence on the time integration the variable grid has. u. ∀x ∈ Ω. t. Matlab provides one reasonable solver for some advection diﬀusion type PDEs in one space dimension. Further we need to deﬁne a grid and a time span. d and f are functions depending on space x. many more can be easily approximated numerically. u. ux ) = 0 for the left boundary x = a and pb (x. ux ) −→  f (x. NUMERICAL METHODS 53 9. T ]. Both grid and tspan need at least three entries and all the entries must be in increasing order. Consider a PDE of the form c(x. u. tspan for which the problem is to be solved. ux ) = 0 for the right boundary x = b. 9.initial. ux ) ∂u ∂t = x−m ∂ (xm f (x.1 Make sure you understand all the examples. t. ua. d(x. t. various conditions for the boundaries have to be speciﬁed.F.tspan. These conditions need to be supplied as a function. t. t. t. best you test them carefully and make use of the ”help” command. u. time t. u.7 Exercises Aufgabe 9. current value of the unknown u and its spatial derivative ux .CHAPTER 9. t. t. Depending on the form of the PDE. Only at the points speciﬁed in grid. qb Note that F and bound need to be deﬁned within M − f iles as their output need to have three or respectively four components. 1 or 2. t)F (x. that are the values of u at t = 0. xb. t) −→   pb  . ux ) ∂x where m = 0. u) + qb (x.options)” where options is an optional struct specifying some tuning parameters.6 Partial diﬀerential equations Partial diﬀerential equations are important in many applications. t. ux)) + d(x. u. One simple problem is the heat equation ∂u ∂t = ∂2u ∂x2 ∀t ∈ [t0 . ”pdepe”. u. u) + qa (x. these values should be provided by a function.

1) = 0 at the right end. How much time does the calculation take? (In order to determine the timing you can use ”tic” and ”toc”. we can write this as u(t) = @(t. Approximate the solution by diﬀerent means and compare the quality of them. What are the zeros of p. Calculate the coeﬃcients of p.) Aufgabe 9.1 : 1].3 Consider the ordinary diﬀerential equation (9.2 Given the polynomials p(x) = (x−3)(x−2)(2x2 +2x+1) and q(x) = (x+1)(x3 +x). 1] with initial values according to u0 (x) = 1/(0. x0)exp(A ∗ t) ∗ u0 (”u = expm(A*t) * u” in Matlab).-0.1 + (x − 0. x0)V ∗ exp(D ∗ t) ∗ V −1 ∗ u0 (now there is no diﬀerence between exp and expm). Using the Jordan decomposition.CHAPTER 9. . q and of p · q.4 Calculate a solution for the heat equation on the unit interval.D]=eig(A)”. Ω = [0.-1. 0) = 0 at the left and u(t. Plot the results for times [0 : 0. NUMERICAL METHODS 54 Aufgabe 9.5)2) and boundary condition ux (t. Let ”A=[-0.1]” then the solution can be written as u(t) = @(t.1. q and p · q? Aufgabe 9. Further we can use any of the ode solvers and we know the exact solution. 1) − 10ux(t.1).1. see ”[V.

% function Y = congruence (n. Nevertheless some quite poorly behaving random number generators are still in widespread use. Here we provide a code which illustrates some of the problems when designing pseudo number generators.a. they can be reproduced.Chapter 10 Examples 10. otherwise an internal state value is used. This is a reasonable pseudo number generator if only a single equally distributed random number is needed.B. B and M are the parameters of % the pseudo number generator and the seed S is used if % speciﬁed.S) % returns N equally distributed values in the interval (0. % The input variables A. One important eﬀect for scientiﬁc research is.1).M. One standard class of pseudo random number generator are linear congruence methods which use the operation Xi = (a ∗ Xi−1 + b) mod M. As the random numbers are important there are many ideas how to create them such that they have good probabilistic properties. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 % linear congruence method % % Y = congruence (N.S.varargin) global congX if (nargin < 4) fprintf(’Not enough input variables\n’). Y = -1.M. However a computer is never able to produce random numbers. return end if (nargin<5) if isempty(congX) 55 .b. % % If congruence is called for the ﬁrst time and S is not % speciﬁed then S=round(M/3+1). only sequences of pseudo random numbers which appear to be random but are deterministic.A.1 Random number generator In many scientiﬁc problems large amounts of random numbers are required.

set a = a + 1 Ui = X = a reduce i and j by 1 if i = 0 or j = 0. set i = k respectively j = k Some of these methods are already known for many years however in the last 15 years they have been improved massively and are now the best around. Another class of random number generators are the Fibonacci methods which use a = U i − Uj if a < 0.2. As the command ”global ” already deﬁnes the variable either having the content of an outside variable with the same name or with no content. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 % A simple Fibonacci random number generator % % Y = Fibonacci(N.1).sqrt(2). for i = 1:n X = mod(a*X+b. unless they have been deﬁned as global using the command ”global”. % Whenever U is speciﬁed it is taken as the new state.29. Thus the variable exists but might be empty and hence our check on line 19.3. else X = congX. return end if (nargin<2) if isempty(FibonacciX) .sqrt(5).U.varargin) global FibonacciX FibonacciI FibonacciJ FibonacciK if (nargin<1) fprintf(’Not enough input variables\n’). so being empty.M). Y(i) = X/M. When calling Fibonacci the ﬁrst time and % U is not speciﬁed then the internal state U is chosen as % U = [7. If we use the variable ﬁrst before we deﬁne it as global this will create an error.4. end else X = S.1). end Y = zeros(n. Y = -1.17]/31. 56 Usually variables of a function just exist within the function. because the same variable might be already known outside the function and thus two variables would clash.U) % returns N equally distributed random numbers in the % interval (0.CHAPTER 10.21. This is done here to save the state variable of the pseudo number generator so that a second call of the pseudo number generator does not return the same values. end congX = X. EXAMPLES 21 22 23 24 25 26 27 28 29 30 31 32 33 34 X = round(M/3+1). % function Y = Fibonacci (n.18.9.

57 In order to test the random number generators here are some numbers they should live up to. I = I-1. end else X = U.4. else X = FibonacciX. end if (J==0) J = K.3. I = round(K/3).sqrt(5).18. J = 8. end Y = zeros(n. K = FibonacciK.21. K = length(U). FibonacciI = I. if (y<0) y = y+1. K = 11.17]/31. for i = 1:n y = X(I)-X(J).2. end end FibonacciX = X.9. N is the number of random variables to be chosen and . I = 3. end Y(i) = y. 1 2 3 4 5 % % % % % Test tool for random number generators out= GenTest(Generator. mean skewness median 1 2 variance kurtosis 1 12 0 1 2 1. I = FibonacciI. J = FibonacciJ. J = J-1.1).N.sqrt(2). EXAMPLES 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 X = [7.29. FibonacciJ = J.CHAPTER 10. if (I==0) I = K.8 The following function uses a speciﬁed random number generator and calculates above variables and provides a little graphic illustrating the quality. J = round(4/5*K). FibonacciK = K. X(I) = y.K). Generator needs to be a random number generator.

else scatter(Y(:. > > GenTest(f.k) X = Gen(n). out. MX = mean(X). > > GenTest(f.100. M4 = mean( Z.1). Z = X-MX.corr = norm(C – eye(k)).0.1/12. out.2).1.2. 3 ).. out.2) > > > .11).2048).median = median(X).. checking if there % is a correlation between K consecutive numbers..100.’corr’. > f = @(n) congruence(n.0. ﬁugre(1). 4). out. clf. out..CHAPTER 10.Y(:.100. 1) ∗ d(1 : k) − ones(n − k. .Y(:.1.2) > > GenTest(f.1).2) > > f = @(n) Fibonacci(n). ’median’. %%%% % Now we start with the correlation analysis %%%% d = [1:n-k]’.1/2. > ’skewness’. M2 = mean( Z.’variance’. k).2).0).1). end 58 Now we can compare the methods easily > wanted=struct(’mean’. ind = d ∗ ones(1.8. C = cov(Y).. k) + ones(n − k. if (n < 101) plot(Y(:.n.kurtosis = mean( Z.1e4. 2).1). Y = X(ind). > > GenTest(f. > > GenTest(f. % % out is a struct containing the interesting values % function out = GenTest(Gen.17) > > f = @(n) rand(n. out. ). EXAMPLES 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 % K is used for the correlation test.2) > > f = @(n) congruence(n.’kurtosis’.mean = MX.1/2.variance = var(X).kurtosis = M4/M2 2..1229.1e4.

scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->