60
University of Oxford Mathematical Institute MSc in Mathematical and Computational Finance Michaelmas Term 2008 Introduction to MATLAB Mihaela Duta mihaela.[email protected] http://www.maths.ox.ac.uk © University of Oxford

Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

University of Oxford

Mathematical Institute

MSc in Mathematical and Computational Finance

Michaelmas Term 2008

Introduction to MATLAB

Mihaela Duta [email protected]

http://www.maths.ox.ac.uk

© University of Oxford

Page 2: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

2 Michaelmas 2008

Contents

1 Getting started..........................................................................4

1.1. Background and short history ............................................................ 4

1.2. Overview............................................................................................. 4

1.2.1. The environment...................................................................................... 5

1.2.2. The workspace ......................................................................................... 5

1.3. Data types and storage ....................................................................... 6

1.3.1. Structures ................................................................................................. 9

1.3.2. Cell arrays................................................................................................ 11

1.3.3. Handling strings .....................................................................................13

1.4. Arithmetical operators ......................................................................15

1.5. Interacting with the operating system..............................................16

1.6. Scripts and functions ........................................................................16

1.7. Useful functions................................................................................ 18

1.7.1. General purpose ......................................................................................18

1.7.2. Constants.................................................................................................18

1.7.3. Basic numeric manipulations ................................................................18

1.7.4. Basic matrix manipulations ...................................................................18

1.7.5. Basic stats ................................................................................................19

1.8. Exercises...........................................................................................20

Exercise 1 The MATLAB environment...............................................20

Exercise 2 Basic computations............................................................20

Exercise 3 Matrix manipulations ........................................................20

Exercise 4 Simple structures and arrays .............................................21

Exercise 5 Structure arrays with cell arrays fields............................. 22

Exercise 6 Strings................................................................................. 22

Exercise 7 Manipulating a directory structure................................... 23

Exercise 8 Writing functions ............................................................... 23

Exercise 9 Fun with numbers.............................................................. 24

2 Flow control and string evaluation ........................................ 25

2.1. Relational operators......................................................................... 25

2.2. Logical operators ............................................................................. 25

2.3. Logical indexing............................................................................... 26

2.4. Flow control ..................................................................................... 26

2.4.1. if-else statement ............................................................................. 26

Page 3: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 3

2.4.2. switch statement ............................................................................... 27

2.4.3. for statement.................................................................................. 27

2.4.4. while statement ................................................................................. 28

2.4.5. break, and return statements................................................ 28

2.5. String evaluation: eval and feval functions...............................28

2.6. Useful functions............................................................................... 29

2.7. Exercises...........................................................................................30

Exercise 10 Relational operators ..........................................................30

Exercise 11 if-else and the for loop ...............................................30

Exercise 12 if-else and the while loop ..........................................30

Exercise 13 The switch statement and return .................................31

Exercise 14 Choosing the flow control method.....................................31

Exercise 15 String evaluation.................................................................31

3 Input/Output and graphics....................................................32

3.1. Saving and loading the workspace................................................... 32

3.2. Low-level I/O ................................................................................... 32

3.3. Interfacing to formatted ASCII files................................................ 33

3.3.1. csvread/csvwrite functions ................................................................... 33

3.3.2. dlmread/dlmwrite functions ................................................................ 34

3.3.3. textread function ................................................................................... 35

3.4. Interfacing with Excel files .............................................................. 36

3.5. Graphics ........................................................................................... 39

3.5.1. Basics ...................................................................................................... 39

3.5.2. Working with graphics properties ....................................................... 42

3.5.3. Some 3D plots.........................................................................................51

3.6. Exercises .......................................................................................... 57

Exercise 16 Loading a workspace and plotting simple graphs ...........57

Exercise 17 Reading formatted files ......................................................57

Exercise 18 Interfacing with character delimited files and reading text files into multiple outputs...........................................................................57

Exercise 19 Reading text files into multiple variables..........................57

Exercise 20 Interfacing with excel files ................................................ 58

Exercise 21 More plots........................................................................... 58

Exercise 22 Even more plots ................................................................. 58

Exercise 23 Customizing a 2D plot using graphics properties............ 59

Exercise 24 3D plots...............................................................................60

Page 4: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

1 Getting started

1.1. Background and short history

MATLAB is a very powerful technical computation tool. Its own creators and developers describe it as:

o “a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment.”

o “an interactive system whose basic data element is an array that does not require dimensioning. “

o [a tool that] “features a family of add-on application-specific solutions called toolboxes […that] allow you to learn and apply specialized technology. Toolboxes are comprehensive collections of MATLAB functions […] that extend the MATLAB environment to solve particular classes of problems. “ Example toolboxes: statistics, signal processing, control systems, neural networks, fuzzy logic, …and many others.

(excerpts from http://www.mathworks.com/access/helpdesk/help/techdoc/matlab.html).

The MATLAB language was invented by Cleve Moler in the late 70s. He was at the time the chairman of the Computer Science Department at the University of New Mexico and his initial goal was to enable his students easy access to software libraries for linear algebra and eigenvalues (LINPACK and EISPACK) without relying on knowledge of Fortran. MATLAB quickly became very popular in academic circles and had a strong influence in the field of applied mathematics.

Cleve Moler was joined by Jack Little and Steve Bangert in re-writing MATLAB in C and they eventually founded the MathWorks in 1984 to commercialise it. Since then, MATLAB has become the leading software tool for technical computing, thanks to its vast collection of computational algorithms. Powerful state-of-the-art numerical libraries are the core of MATLAB; the GUIs, environment etc are just very useful tools to manipulate them.

A good article about the background and history of MATLAB can be found at http://www.mathworks.com/company/newsletters/news_notes/clevescorner/dec04.html

1.2. Overview

The MATLAB system consists of:

1. Development Environment - a set of tools for manipulating the MATLAB functions and files; it consists of:

• Command Window • Editor/Debugger • Browsers for help, workspace etc

2. Mathematical Function Library - a vast collection of computational algorithms ranging from elementary functions like sum, sine, cosine, etc to more sophisticated functions like matrix inverse, matrix eigenvalues, fast Fourier transforms, etc. 3. The MATLAB Language - a high-level matrix-oriented programming language 4. Graphics - a vast collection of high-level functions for two- and three-dimensional graphics, image processing and animation, as well as low-level functions for customizing the graphics. 5. The MATLAB Application Program Interface (API). - a library enabling the interaction between C and Fortran routines and MATLAB. It includes facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files.

Page 5: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 5

1.2.1. The environment

An example of a working layout for the MATLAB environment is given in Figure 1

The Command Window is used to invoke MATLAB functions and scripts. The Figure Window displays the graphics. The Workspace Browser allows the user to manipulate the existing variables. The Help Browser gives access to documentation, tutorials and demos. Quick help on specific functions can be obtained from the Command Window with the help function. There are also other windows, such as the Command History Window and the Directory Browser. MATLAB also have a built-in Editor/Debugger to edit scripts and functions. The combination of windows displayed at any one time is controlled from the Desktop Desktop Desktop Desktop menu.

Information about toolboxes, functions etc can be quickly obtained using the help function in the Command Window. Detailed information, including tutorials, can be obtained via the graphical Help Browser.

Note that most of the examples and exercises in this course will use the Command Window and you are supposed to make full use of the MATLAB help when solving the exercises.

A variety of useful demos for the desktop can be run from the Command Window with >> demo matlab desktop

1.2.2. The workspace

The workspace stores variables accumulated during a MATLAB session. The contents of the current workspace can be visualised and manipulated

• from the Command window using who and whos functions

• from he Workspace Browser - the graphical alternative to the whos function; it is invoked either with the workspace function from the Command Window, or by selecting Desktop Desktop Desktop Desktop

| Workspace| Workspace| Workspace| Workspace from the MATLAB menu.

For example, the following sequence

Figure 1 Example of a working layout

Page 6: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

6 Michaelmas 2008

>> a = [1 2; 3 4]

a =

1 2

3 4

>> t = [1:1:41];

>> y = [1:1:41];

creates three variables: a, t and y. Information about them can be obtained with

>> whos

Name Size Bytes Class

a 2x2 32 double array

t 1x41 328 double array

y 1x41 328 double array

Grand total is 86 elements using 688 bytes

The Workspace Browser for this session is given in Figure 2.

The two main areas of the Workspace Browser are

• the display area for the current variables

• the data manipulation toolbar - enables the creation of new variables, loading and saving of the workspace, as well as producing various graphics.

In this example the workspace contains 3 variables: a, t and y. a is a 2x2 matrix, while t and y are one-dimensional vectors with 41 components each. Matrix a being sufficiently small its value is also displayed, while for the other two only the dimensions appear.

Some of the commands used so far were ended with the character; - this has the effect of suppressing the echoing in the command window of the result of the statement. If a command is

not ended by ;, the result of the operation performed will be echoed in the Command

Window.Note that using ; to suppress the output of a command is common practice when writing

elaborate MATLAB scripts/functions, when many operations are performed in a sequence.

1.3. Data types and storage

MATLAB supports the following data types:

1. Numerical data – by default, numerical data is double-precision matrix; single-precision floating-point and 8-, 16-, and 32-bit integers, both signed and unsigned numerical values are also supported;

2. Logical data a. logical function converts numerical matrices to logical matrices. b. true and false functions create matrices of all true and all false elements,

respectively. true(1) and false(1) are the same as logical(1) and logical(0), respectively.

3. Strings – matrices of alpha-numeric characters

Figure 2

Page 7: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 7

4. Cell arrays – miscellaneous collection of data 5. Structures – composite data types consisting of fields 6. Objects – structures with registered methods

Variables do not need to be declared prior to being used. Assigning a value to a variable will prompt MATLAB to create the variable and allocate the memory required, according to the type required by the given value.

For example, >> a = 2;

creates the variable double-precision matrix a having a single element with the value 2. >> whos a

Name Size Bytes Class

a 1x1 8 double array

Grand total is 1 element using 8 bytes

If we then use >> a = [2 3];

MATLAB will assign a a new value, making it a 1x2 matrix. The type of the variable can also be changed by assigning it a new value of a different type; if after the previous two commands we type

>> a = ‘Some text’;

the variable a is changed to a string containing the text “Some text”. Users can control the format in which they see numerical values echoed in the Command Window or in the Workspace Browser using the format function. For example let’s create a variable a to contain the value of π returned by the MATLAB built-in function pi:

>> a = pi;

By default, MATLAB will echo the value of a in the following form: >> a

a =

3.1416

that is scaled fixed point format with 5 digits. The format function changes the way all numerical variables are displayed in the Command Window from the point in time format was invoked to the next call to format or the end of the current MATLAB session.

For example, >> format long

Will have our variable echoed >> a

a =

3.14159265358979

that is scaled fixed point format with 15 digits. The reader is encouraged to consult MATLAB help for more details on format – and as a rule all the functions mentioned in this course. The fundamental data storage unit in MATLAB is the matrix: two-dimensional data structure storing multiple elements. These elements can be numerical, characters, logical and structures. Everything in MATLAB is stored as a matrix; even single-value variables are stored as 1x1 matrices.

A one-dimensional matrix is called an array or vector. An nx1 matrix is called a row vector and a 1xn matrix is called a column vector.

Matrices are created with the matrix creator operator []. For example, >> a = [1 2; 3 4];

creates a 2x2 matrix of 4 numbers, 1 2

3 4a

=

. When creating the matrix, the elements within a

row are separated by spaces while the rows are separated with a semi-colon;

Page 8: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

8 Michaelmas 2008

An empty matrix is created with

>> a = [] a =

[]

A matrix with all elements zeros is created with the function zeros, e.g. >> a = zeros(1,5)

a =

0 0 0 0 0 The two arguments of the function are the number of rows and columns. Similarly, a matrix with all elements 1 is created using function ones. Individual element of matrices can be accessed with numerical indices enclosed in round brackets (), e.g. >> a = [10 20 30 40];

>> a(2)

20

For a two-dimensional mtrix the two indices will be separated by comma : >> a = [10 20; 30 40];

>> a(1,2)

20

The colon character : can be used when creating a matrix to specify the range span for the values

of a matrix in the form [start_value : step_value : end_value] . If no step_value is given the default step of 1 is assumed. For example,

>> b = [0:5:15];

creates an array with 4 numbers, from 0 to 15 in steps of 5, [0 5 10 15]b = . And

>> b = [1:5]

b =

1 2 3 4 5

Assumes the step_value of 1 and creates an array with numbers from 1 to 5 in steps of 1.

Individual elements of matrices can be accessed providing indices for their position in the matrix – first index for the ordinal position within its row, and second index for the ordinal position within its column. For example A(1,2) will give the second element of the first row:

>> a = [10 20 30 40 50; 100 200 300 400 500];

>> a(1,2)

ans =

20

Note that this command of retrieving a certain element of a matrix did not assign its result to any variable – in such cases, MATLAB automatically assigns the result to the default variable ans (short for answer), hence that is the variable that Command Window displays in the above example.

Entire rows/columns or parts of them can also be accessed with one command using the colon : to specify the ranges:

>> A(1,:)

ans =

10 20 30 40 50

accesses the entire first row of the matrix, while

>> A(:,2)

ans =

20

200

accesses the entire second column of it. Also

>> A(1,1:2)

ans =

10 20

Page 9: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 9

accesses from the first row only the element whole indices are from 1 to 2.

Other arrays can be used to selectively access elements. For example, if we define >> ind = [1 3];

then >> a(:,ind)

ans =

10 30

100 300

Rows and columns can be added to an existing matrix using the same conventions for separating elements, i.e. space for elements in the same row and semi-colon ; for separating rows:

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

>> a = [5 6];

>> A = [A;a];

>> A

A =

1 2

3 4

5 6

>> b = [7 8 9];

>> A = [A b'];

>> A

A =

1 2 7

3 4 8

5 6 9

Rows/columns can also be deleted from a matrix:

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

>> A

A =

3 4 8

5 6 9

>> A(:,3) = [];

>> A

A =

3 4

5 6

1.3.1. Structures

Structures are complex data types comprising of data containers called fields. The fields can be any type of data, including other structures. Like any other data type, structures can be used to build matrices of any dimension.

For example, let’s build a structure array to hold some purely fictional environmental data collected from five different locations, as given in the following table.

Location Date Temperature

[°C ]

Relative humidity

[%]

CO2 concentration

Oxford 12-Oct-05 18.1 30.4 210.1

London 10-Oct-05 20.3 50.2 250.8

Birmingham 15-Oct-05 17.1 32.0 220.3

Glasgow 02-Oct-05 10.5 55.7 190.2

We can build a structure variable by assigning a value to each element:

Page 10: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

10 Michaelmas 2008

>> struct_data.location = 'Oxford';

>> struct_data.date = '12-Oct-05';

>> struct_data.temperature = 18.1;

>> struct_data.rel_humidity = 30.4;

>> struct_data.co2_concentration = 210.1; Recalling the value of struct_data at the MATLAB prompt returns:

>> struct_data

location: 'Oxford'

date: '12-Oct-05'

temperature: 18.1000

rel_humidity: 30.4000

co2_concentration: 210.1000

We can then start building an array with these structures:

>> env_data(1) = struct_data;

We can add the next line of data from the table with

>> env_data(2).location = 'London';

>> env_data(2).date = '10-Oct-05';

>> env_data(2).temperature = 20.3;

>> env_data(2).rel_humidity = 50.2;

>> env_data(2).co2_concentration = 250.8;

Recalling the value of env_data now will give:

>> env_data

env_data =

1x2 struct array with fields:

location

date

temperature

rel_humidity

co2_concentration

A more compact way of initialising the same structure uses the struct command:

>> env_data(1) = struct('location', 'Oxford', ...

'date', '12-Oct-05',...

'temperature', 18.1,...

'rel_humidity', 30.4,...

'co2_concentration', 210.1 ...

);

>> env_data(2) = struct('location', 'London', ...

'date', '12-Oct-05',...

'temperature', 20.3,...

'rel_humidity', 50.2,...

'co2_concentration', 250.8 ...

);

Note: ... allows a MATLAB statement to be split along multiple lines.

You can add a new field to a structure array by simply assigning a value to this field in one of the structures. For example if we want to add a field pollution_index we can just give it a value in the first structure in the array:

>> env_data(1).pollution_index = 12;

Echoing the whole structure array env_data gives:

>> env_data

env_data =

1x2 struct array with fields:

location

date

temperature

Page 11: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 11

rel_humidity

co2_concentration

pollution_index

The pollution_index field has been added. However, only the first element of the array has a value for pollution_index field, the other elements have the field an empty matrix:

>> env_data(1)

ans =

location: 'Oxford'

date: '12-Oct-05'

temperature: 18.1000

rel_humidity: 30.4000

co2_concentration: 210.1000

pollution_index: 12

>> env_data(2)

ans =

location: 'London'

date: '12-Oct-05'

temperature: 20.3000

rel_humidity: 50.2000

co2_concentration: 250.8000

pollution_index: []

Fields can be deleted from a structure using the rmfield function. For example, we can delete the pollution_index with

>> env_data = rmfield(env_data, 'pollution_index');

We can check whether a certain field exists in a structure array or not by using the isfield function which will return logical 1 if the field exists and logical 0 otherwise:

>> isfield(env_data, 'pollution_index')

ans =

0

>> isfield(env_data, 'co2_concentration')

ans =

1

1.3.2. Cell arrays

Cell arrays allow the storage of dissimilar data in one single data unit. For example, let’s assume we want to store a list with the locations of our environmental experiments. Because the location names have different length, we can’t store them in an array of strings. Attempting to do so will give:

>> a = ['Oxford';'London';'Birmingham';'Glasgow']

??? Error using ==> vertcat

All rows in the bracketed expression must have the same

number of columns.

That is because MATLAB expects all the rows in a matrix to have the same length (and similarly, all columns in a matrix must have the same length). We can store this list in a cell array:

>> a = {'Oxford','London','Birmingham','Glasgow'} >> whos a

Name Size Bytes Class

a 1x4 298 cell array

Grand total is 33 elements using 298 bytes

>> a

a =

'Oxford' 'London' 'Birmingham' 'Glasgow'

Page 12: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

12 Michaelmas 2008

We built the cell array by specifying the content in curly brackets { }, rather than square brackets [ ] used to build matrices – curly brackets are cell array constructors in the same way as square brackets are matrix constructors. Elements of cell arrays are accessed using indices in curly brackets:

>> a{2}

ans =

London

We can build cell arrays using data of different types:

>> b = {'Oxford', [1 2 3 4 5], [1 2;3 4], logical([1 0 1 1 0]) }

b =

'Oxford' [1x5 double] [2x2 double] [1x5 logical]

b is a collection of varied data: a string (‘Oxford’), an array of numbers ([1 2 3 4 5]), a matrix of numbers ([1 2; 3 4]) and an array of logical values ([true false true true false]); To access the numerical array we use

>> b{2}

ans =

1 2 3 4 5 We access the second element of the numerical array with >> b{2}(1)

ans =

2

To access the second element of the second line of the matrix we use >> b{3}(2,2)

ans =

4

We can also build two-dimensional (or multidimensional) cell arrays in a similar way we build matrices – the cell array constructors {} use commas or spaces to indicate column breaks and semicolons to indicate row breaks: >> c = {'Oxford', [1 2 3 4 5]; [1 2;3 4], logical([1 0 1 1 0]) }

c =

'Oxford' [1x5 double ]

[2x2 double] [1x5 logical]

To access the numerical array from the first line of the cell matrix we use

>> c{1,2}

ans =

1 2 3 4 5 We access the second element of the second column of the matrix with >> c{2,1}(2,2)

ans =

4

size and length functions can be used on cell arrays in a similar way as on numerical arrays. Concatenation of cell arrays differs slightly from numerical arrays concatenation. For example, for a numerical array the following code will build an array [1 2 3 4 5 6]:

a = [];

for i=1:5,

a = [a i];

end

To build a cell array {'1' '2' '3' '4' '5'} we can use: a = {};

for i=1:5,

a = {a{:} num2str(i)};

end

Page 13: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 13

1.3.3. Handling strings

A string is an array of alpha-numeric characters. Its elements are accessed using indices, in the same way we access matrix elements.

For example, >> temp = 'Some text';

creates a variable temp that is an array of characters: >> whos temp

Name Size Bytes Class

temp 1x9 18 char array

The second character of temp is accessed with >> temp(4)

ans =

e

Strings can be concatenated to create longer strings:

>> txt_short = 'txt';

>> txt_long = [txt_short 'txt1' 'txt2']

txt_long =

txttxt1txt2

>> whos txt_long

Name Size Bytes Class

txt_long 1x11 22 char array

Grand total is 11 elements using 22 bytes

String can also be concatenated with strcat function:

>> txt_long = strcat(txt_short, 'txt1', 'txt2')

Two strings are compared using strcmp function, which returns logical 1 if the two are identical and logical 0 otherwise:

>> txt1 = 'txt1'; txt2 = 'txt2';

>> strcmp(txt1, txt2)

>> ans

0

>> txt1 = 'txt1'; txt2 = 'txt1';

>> strcmp(txt1, txt2)

>> ans =

1

strcmp function is case-sensitive. The case-insensitive comparison is performed with strcmpi.

strfind function searches for occurrences of a string within a longer string, returning the starting indices of each such occurrence (the order of the input arguments does not matter, always the longer one will be searched):

>> txt = 'Some text';

>> findstr('e', txt)

ans =

4 7

findstr performs the same action as strfind, only that now the order of the input arguments matters: the first string is searched for occurrences of the second string:

>> txt = 'Some text';

>> strfind(txt, ‘e’)

ans =

4 7

Formatted data can be written into a string with the sprintf function:

str = sprintf(format, M, ...)

where str is the string to write into, format is the same as for fprintf and M,... are the variables to write into the string. For example:

Page 14: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

14 Michaelmas 2008

>> a = 2.5; b = 3.0;

>> txt1 = 'a is written as a float';

>> txt2 = 'b is written as an integer';

>> str = sprintf('%s: %f\n%s: %d\n', txt1, a, txt2, b);

>> str

str =

a is written as a float: 2.500000

b is written as an integer: 3 Formatted data can be read from strings with fscanf function:

M = sscanf(str, format)

where str is the string to read from, format is the same as for fprintf and M is the matrix into which the read data is returned. For example:

>> str = 'Float1: 4.56 Float2: 5.25';

>> [nrs] = sscanf(str, 'Float1: %f Float2: %f');

>> nrs

nrs =

4.5600

5.2500

The same result can be obtained by instructing the sscanf function to ignore the character data using %*s in the format string: >> [nrs] = sscanf(str, '%*s %f %*s %f');

sscanf can be very useful when reading formatted data from a file. For example, let’s consider a file sscanf_example_file.dat with the following content: 3 locations Mean value Min value Max value

Oxford

index1: 1.749620128537693e+00 1.703773000364956e+00 1.797833599682110e+00

index2: 1.697959361591491e+00 1.682501019621102e+00 1.713144575510367e+00

index3: 1.749623494012652e+00 1.703776310044729e+00 1.797837028789066e+00

London

index1: 1.749615437822391e+00 1.747581795050969e+00 1.751823230450515e+00

index2: 9.859228502044280e-01 -3.211043400638174e+00 4.808943986025072e+00

index3: 2.309815889927119e-01 2.307131626726590e-01 2.312727105075745e-01

Birmingham

index1: 1.405880908719734e-01 1.389800553077239e-01 1.409034052915850e-01

index2: 8.658467970387173e+02 8.654571929512329e+02 8.662385104458341e+02

index3: 2.423537056932346e-01 -2.306070960820460e+00 2.790843573593264e+00

We can read the information from the file in a structure array using the following code: fid = fopen('sscanf_example_file.dat','r');

tline = fgetl(fid);

nlocations = sscanf(tline, '%d %*s');

tline = fgetl(fid); % ignore second line

for i=1:nlocations,

my_data(i).location = fgetl(fid);

tline = fgetl(fid); % read the line with index1 values

temp = sscanf(tline, '%*s %f %f %f'); % extract numerical data % now assign value, min and max for index1

my_data(i).index1.value = temp(1); my_data(i).index1.min = temp(2);

my_data(i).index1.max = temp(3);

tline = fgetl(fid); % read the line with index2 values temp = sscanf(tline, '%*s %f %f %f'); % extract numerical data

% now assign value, min and max for index1 my_data(i).index2.value = temp(1);

my_data(i).index2.min = temp(2);

my_data(i).index2.max = temp(3);

tline = fgetl(fid); % read the line with index3 values

temp = sscanf(tline, '%*s %f %f %f'); % extract numerical data

% now assign value, min and max for index1 my_data(i).index3.value = temp(1);

my_data(i).index3.min = temp(2); my_data(i).index3.max = temp(3);

end fclose(fid);

Page 15: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 15

Echoing my_data will give: >> my_data =

1x3 struct array with fields:

location

index1

index2

index3 The structure array now contains the data from the file. For example: my_data(i).location

ans =

London

my_data(i).index1.value

ans =

1.749615437822391e+000

MATLAB also offers a simple way of transforming data from numerical to string form and vice versa. num2str converts an array to a string according to a specified format: str = num2str(A, format)

For example: >> temp = num2str([1 2 3], '%f ');

>> whos temp

Name Size Bytes Class

temp 1x27 54 char array

Grand total is 27 elements using 54 bytes

>> temp

temp =

1.000 2.000 3.000

Strings containing numbers can be converted into numerical values with str2num: >> str = '234.5000';

>> nr = str2num(str);

>> nr

nr =

234.5000

1.4. Arithmetical operators

MATLAB provides all the familiar operators for performing numerical computation as well as some extra ones:

1. Addition, subtraction, multiplication and division : +, -, * and /, respectively (the usual precedence rules apply)

2. Left division: \

3. Power operator: ^

4. Complex conjugate transpose operator: ‘

The *, / and ^ operators if used as given above will be applied to the matrix in its entirety, whereas if preceded by a . (e.g. .*) will be applied to each element of the involved matrix in turn.

For example, if A and B are two 2x2 matrices created with

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

>> B = [5 6; 7 8];

Then >> C1 = A*B

C1 =

19 22

43 50

with ij ik kj

k

C A B=∑

Page 16: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

16 Michaelmas 2008

By contrast, using .* operator will give >> D = A.*B

D =

5 12

21 32

that is *ij ij ijD A B= .

1.5. Interacting with the operating system

When required at the command prompt to execute a function, MATLAB searches for the function’s source file in the current directories, then, if not found there, in its directory search path. The directory search path can be manipulated using the path function. Invoked on its own, path echoes the current directory search path. path('newpath') sets the path to a 'newpath', while path(path, 'extrapath') appends to the existing path 'extrapath'.

The current working directory is returned by pwd function. The content of the current working directory (or any other specified directory) is given by the dir function. dir returns a structure array containing the name, modification date, length in bytes and a flag that is logical 1 if the element is directory and 0 otherwise. For example, for the working directory with the examples for this session:

>> temp = dir;

>> temp temp =

9x1 struct array with fields: name

date bytes

isdir >> for i=1:length(temp),

fprintf('%s\n', temp(i).name); end

.

..

build_env_data_1.m

build_locations_cell_array.m

num2str_str2num_example.m

os_examples.m

sprintf_sscanf_examples.m

sscanf_example_file.dat

strings_example.m

The working directory is changed using the cd function: cd('directory'). On its own, the cd function returns the current directory.

Files can be copied with copyfile, moved using movefile and deleted using delete copyfile('source','destination')

movefile('source','destination')

delete('filename')

Directories can be created with mkdir and deleted with rmdir: mkdir('dirname')

rmdir('dirname')

The filenames and the directory names can be specified in both absolute path and a path relative to the current directory.

An operating system command can also be executed from the command window by preceding it with the ! character. The result is echoed in the MATLAB command window. Example:

>> !date

The current date is: Sun 11/06/2005

Enter the new date: (mm-dd-yy)

1.6. Scripts and functions

A series of MATLAB commands can be grouped together in a script and saved in an M-file. This file should have the extension .m , hence its name. When a script is invoked, the commands found in the file are executed, using the variables already found in the workspace and/or creating new

Page 17: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 17

ones. A script does not have input arguments and cannot return variables, but the variables it creates remain in the workspace of the calling MATLAB session for subsequent computations.

As an example, let’s go back to the investigation of the * operator and it variant .* and create a script file operator.m with the following content:

% Investigate the effect of * and .* operators

A = [1 2; 3 4];

B = [5 6; 7 8];

RES1 = A*B;

RES2 = A.*B;

Running the script from the command line

>> operators

(note that to do this we use the name of the script file and omit the extension) will not produce anything on the screen, but the workspace of the main MATLAB session, contains two new variables, RES1 and RES2 – created inside the script - with the results of the calculations, i.e.

>> RES1 =

19 22

43 50

>> RES2 =

5 12

21 32

A function is an M-file with input and output arguments that have a different memory area that the main MATLAB session. Variables created and changed inside a function are not visible outside the scope of the function, but can be returned to the caller for subsequent usage. Also, variables from the calling MATLAB session are not visible inside the functions, but can be passed to the function as input arguments.

The name of the function should be the same as the name of the file (without the extension). The first line of the M-file gives the function definition, which should comply with the following syntax:

function [<outputs list>] = function_name(<input arguments list>)

To illustrate the use of functions, we can revisit the * and .* operators. We can define a function operators_function that has as inputs the two matrices and returns the result of the two calculations – we save the function in a file called operator_function.m

function [RES1 RES2] = operator_function(A,B)

% Investigate the effect of * and .* operators

RES1 = A*B;

RES2 = A.*B;

The first line specifies that the function name is operator_function and that the function has two input variables, A and B, and two output variables, RES1 and RES2.

If we invoke the function from the MATLAB prompt with >> operator_function([1 2; 3 4], [5 6; 7 8]);

the same calculations are performed as in the script example, but the workspace does not contain any new variables. RES1 and RES2 are destroyed when the function finished running. To access the result, we need to instruct MATLAB to store those two variable in the output variables specified in the function call:

>> [r1 r2] = operator_function([1 2; 3 4], [5 6; 7 8]);

After the above command, the workspace will contain two new variables, r1 and r2 containing the results of the calculations performed inside the function.

Page 18: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

18 Michaelmas 2008

1.7. Useful functions

1.7.1. General purpose

• help - lists all primary help topics o help / - lists all operators and special characters, along with their

descriptions. o help <functionname> - displays M-file help for <functionname>

• ans - returns the the most recent answer MATLAB has given.

• clc – clears the Command Window

• ; - at the end of a command prevents echoing of the command result

• ! - any text following it is issued as a command to the underlying computer operating system

• format - control display format for output o format <type> - changes the format to the specified type, e.g. short, long,

short e, long e, hex, compact, etc

• who - return a simple list of the variables in the workspace

• whos - list variables in workspace giving details about their type, size etc

• clear - remove items from workspace, freeing up system memory o clear – alone removes all variables from the workspace o clear <a> – removes the variable a from the workspace o clear all – removes all variables and functions

• pause – stops the execution of the m-file and waits for the user to press any key before continuing (useful for debugging)

• disp - displays a text or an array

1.7.2. Constants • pi - π

• eps - floating-point relative accuracy: returns the distance from

1.0 to the next largest double-precision number, that is eps = 2^(-

52)

• realmax - largest positive floating-point number

• realmin - smallest positive floating-point number

• intmax - largest possible integer number • intmin - smallest possible integer number • Inf - returns the IEEE arithmetic representation for positive

infinity

• Nan – returns the IEEE arithmetic representation for Not-a-Number

• i – imaginary unit

1.7.3. Basic numeric manipulations • sqrt – square root

• abs – absolute value

• conj – complex conjugate

• real – real part

• imag – imaginary part

• fix – rounding towards 0

• round – rounding to nearest integer

• floor – rounding towards -∞

• ceil – rounding towards +∞

1.7.4. Basic matrix manipulations • size - gives the matrix dimensions

Page 19: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 19

• ones - creates a matrix of all ones

• zeros - creates a matrix of all zeros

• rand - creates a matrix of uniformly distributed random numbers

• randn - creates a matrix of normally distributed random numbers

• eye - creates a matrix with ones on the diagonal and zeros elsewhere

• reshape – re-shape a matrix

• end – is the index of the last element of an array or of a row/column of a matrix

1.7.5. Basic stats • min – returns the minimum value of a set of data

• max – returns the maximum value of a set of data

• mean – returns the mean value of a set of data

• std – returns the standard deviation of a set of data

• sum – returns the sum of the elements

• cumsum – returns the cumulative sum of the elements

Page 20: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

20 Michaelmas 2008

1.8. Exercises

Exercise 1 The MATLAB environment

• Familiarise with the MATLAB environment • Use the MATLAB help

Task 1 Customize the environment

Step 1 Open MATLAB from Star t | P rog ramFi les |Ma t l abStar t | P rog ramFi les |Ma t l abStar t | P rog ramFi les |Ma t l abStar t | P rog ramFi les |Ma t l ab

Step 2 Identify all the windows and customize your configuration using the Desk top Desk top Desk top Desk top menu, eg:

• activate and customize the editors

• dock/undock windows

• activate the workspace browser • activate the help browser

Task 2 Familiarise with the help

Using the help, explore the format function.

Task 3 Pie (sic)

Step 1 Ensure you have the Workspace Browser visible. In the Command Window display the value of π .

Assign the value of 2π to a variable my_2pi.

Step 2 Use format to change the way my_2pi is displayed. Check the effect both in the Workspace Browser and the Command Window.

Exercise 2 Basic computations

Task 1 Single values

Create two variables a = 2 and b = 3. Assign to c the sum of a and b. Type a = a+b; what is the value of a now? The type c = a+b; what value for a is the latest operation using?

Task 2 Arrays

Step 1 Create t = π and compute sin(t). Then change t to [0 / 2π π 3 / 2π 2π ]; what is the

effect of applying sin to t now?

Exercise 3 Matrix manipulations • Create matrices

• Simple matrix manipulations

Task 1 Create matrices and access their elements

Step 1 Use help to find out how to generate random numbers

Step 2 • Create a 1x10 matrix m1 with random numbers uniformly distributed between 0 and 1

• Create a 1x10 matrix m2 with random numbers uniformly distributed between 0 and 100

Step 3

• Create a matrix t1 spanning from 0 to 2π in steps of 110−

• Create a matrix t2 spanning from 0 to 2π in steps of 510−

Step 4 Create a 5x5 random matrix m3.

• display the third line

• display the second column

• display the second and third column of the fourth and fifth rows. For these, note that elements of matrices can be displayed using arrays as indices.

Task 2 Rounding off

Step 1 Using the matrices created in Task 1, Step 1, explore the effect of various rounding functions.

Step 2 Using rounding functions, create a 1x5 matrix of integer numbers randomly distributed between 0 and 100;

Step 3 Using a similar approach, create a 1x15 matrix of integers between -100 and 100.

Page 21: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 21

Task 3 Matrix operators

Step 1 Create two arrays a = [1 2 3 4 5] and b= [6 7 8 9 10]

Step 2 Add 10 to each element of array a. Compute the cube of each element of array b.

Step 3 Concatenate the two arrays to form array c with 10 elements. Take the square root of the elements of c whose index is even.

Step 4 • add the arrays a and b together.

• add the sum of the elements of b to each element of a

• multiply each element of a with the corresponding element of b

• calculate the cumulative sum of the ratio (element by element) of the two arrays.

Task 4 Simple stats

Step 1 Using the help, find out how to calculate the mean and standard deviation of a set of data

Step 2 Calculate the sin of t1 and t2 created in Task 1, Step 2. Calculate the mean of the two variables

obtained. Knowing that the mean of sin over [0 : 2 ]π is zero, try and explain the results you

obtain.

Step 3 • compute the maximum and minimum of all elements of sm3

• compute the mean of all elements of m3

• calculate the sum over the rows of m3.

Exercise 4 Simple structures and arrays

Task 1 Create a simple structure

Step 1 Start by clearing the workspace. Load into MATLAB the mat file Exercise1_Task1_input_file.mat (using the load function). Use the function who to see

what variables have been added to your workspace. You should have 6 variables describing a record for a student: name, surname, affiliation, status, course taken and a flag for fees (paid/not-paid)

Step 2 Create a MATLAB structure to contain all this information into one variable student_data with 6 appropriate fields.

Task 2 Create a simple cell array

Step 1 Start by clearing the workspace. Load into MATLAB the mat file Exercise1_Task2_input_file.mat (using the load function). Use the function who to see what variables have been added to your workspace. You should have 6 string variables with names in the form ‘surname, name’

Step 2 Attempt to put all the names in an array of strings; what happens? Why?

Step 3 Create a cell array to keep all the names.

Step 4 Sort the cell array to contain all the names in alphabetical order using a MATLAB built-in function.

Step 5 Pass through the sorted cell array and print out the names on the screen in the format: Student <number> is <name> Where number if the ordinal number of the student in the sorted cell array

Page 22: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

22 Michaelmas 2008

Exercise 5 Structure arrays with cell arrays fields

Task 1 Familiarise with data

Step 1 Start by clearing the workspace. Load into MATLAB the mat file Exercise2_input_file.mat (using the load function). Use the function who to see what variables have been added to your workspace. You should have 5 variables with information for 6 students:

• A cell array with names in the format ‘surname, name’

• A cell array with corresponding affiliations

• A cell array with corresponding status (i.e. under/postgraduate, research/academic staff)

• A cell array giving the corresponding courses taken by each person • A logical array giving the status of the payment of the fees for the courses (one fee for all

courses for a particular person)

Step 2 Make sure you understand what each variable is and how the data is stored in it: use the who function and echo the variables on the screen for that. Make sure you know how to access elements from each variable; e.g. echo on the screen the name of the second course taken by the third person.

Task 2 Sorting and extracting data

Step 1 Sort the cell array with names from Task1 in alphabetical order. Use the index variable returned by the sort function to re-arrange the rest of the variables to match the new order of the names.

Step 2 Split the sorted names cell array into two cell arrays, one keeping all the names, the other keeping all the surnames. Hints:

• Note that the end of the name is always one character behind the comma, and the start of the name is two characters after the comma

• To build a numerical array by repeated concatenation you can use a code like this a = []; for i=1:5:20, a = [a i];

end

Similarly, to built a cell array to keep the same numbers as character string, the code to use is: a = {}; for i=1:5:20,

a = {a{:} num2str(i)}; end

Task 3 Build a structure arrays

Step 1 Using the data from Task2, build an array of structures, one structure per person with the following fields:

• surname

• name

• affiliation

• status • courses – a cell array for each person

• fees Use the sorted version of your data.

Step 2 Pass through the structure array and print out on the screen the people who did not pay their fees in the format; <name> <surname>, <affiliation> Add a title line to your printed list describing the content of the list.

Exercise 6 Strings

Task 1 Creating a longer strings from shorter ones

Step 1 Start by clearing the workspace. Load into MATLAB the mat file Exercise3_input_file.mat. Use the function who to see what variables have been added to your workspace. You should have 4

string variables (phrase1, etc).

Step 2 Concatenate the four phrase variables into a longer string variable paragraph, separating each

phrase from the previous with a space

Task 2 Manipulating strings

Step 1 Use a string search function to count the occurrences of the word 'you' in paragraph.

Step 2 Pass through phrase1 and extract all individual words in a cell arrays personal_dictionary.

To achieve this, note that a word inside the string starts a character after a space and finishes a character before a space. Deal with start/end words separately.

Page 23: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 23

Exercise 7 Manipulating a directory structure

Task 1

Step 1 Get the directory listing for subdirectory Exercise1_Task2_DB into a variable dir_listing.

Study dir_listing and make sure you understand what it contains.

Step 2 Get the names off all subdirectories of Exercise1_Task2_DB into a cell array dirs. Get the

number of subdirectories into ndirs.

Step 3 Navigate to subdirectory Contents and write in Summary.txt the list of all the subdirectories of

Contents in reverse alphabetical order. Hints: • Before changing directory store in a variable the current directory (you can use pwd

function fort this) to be able to come back…

• dir function returns the files in ascending alphabetical order.

Step 4 Copy ReadMe.txt from GeneralInfo subdirectory to to all subdirectories of GeneralInfo. To do this first store all the subdirectories names into a list and then use a for loop to walk through it.

Exercise 8 Writing functions

• Creating a function • Using functions outputs

Task 1 Money matters

Step 1 Open a new file in the Editor/Debugger.

Step 2 Compute the amount of money accumulated over a period of time in a bank account with a fixed interest rate.

The formula associated with fixed interest rates is 0 (1 )n

ns s r= + , where 0s is the initial sum

of money, r is the interest rate over a year and n is the number of years.

Step 3 Write a function account that has as inputs the initial sum, the interest rate and the number of years and displays the final sum accumulated in the account. Call the function from the command line with different values

Step 4 Using the element-wise operators, change the account function to deal with n as a vector of

years.

Step 5

Change the function account again to ensure that it can deal with 0s as an array. Try calling your

function with n = [1 2 3 4 5] and 0s = [10 50 100]. You may need to use reshape to ensure the

inputs have required dimensions. Note the output will be a matrix: one row will represent the increase of a certain initial sum over the specified years.

Task 2 Party time

Step 1 Let us assume that we have a round chocolate cake with the radius r , height h and density d .

Write a function cake to return the mass of the cake. Do this by splitting the calculations into steps, each implemented in a different function:

• compute the area of the surface of the cake (2

a rπ= )

• compute the volume ( *v a h= )

Finally use these two functions to compute the weight of the cake ( *w v d= ).

Step 2 Write another function portion to compute the weight of a fraction of the cake. Make this function have the same inputs as cake, plus the percentage. Find out how much an eighth of a cake of 30cm diameter, 10cm height and 10g/cm3 weighs. Is your portion function able to process portion fraction inputs in the form of a vector? Also, try calling the functions with r =[20 30] and d = [10 50 100]. As in the previous exercise, the expected output should be a matrix.

Page 24: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

24 Michaelmas 2008

Exercise 9 Fun with numbers

Task 1 Floating-point arithmetic

Step 1 Find out about floating point precision on your computer (you can do this by exploring the results returned by a search for “floating point precision” in the help)

Step 2

Find out what is the relative floating-point accuracy by using the eps function. Make sure you understand what it means.

Step 3

Find out what are the limits for floating-point and integer representation on your computer. Use the help to explore realmax/realmin and intmax/intmin.

Step 4

Create a variable a to store the result of 3 310 1 10+ − . Create another variable b to store

20 2010 1 10+ − . Are they different? Can you explain why? Change the way b is calculated such

that it gives the right answer.

Step 5

Create a variable c to store 201 10−

+ . Try displaying it in different formats. How do you explain

the result?

Page 25: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 25

2 Flow control and string evaluation

2.1. Relational operators

In addition to the arithmetical operators presented in the previous session, MATLAB also provides relational and logical operators.

The relational operators perform element-by-element comparisons between two matrices, returning a matrix of logical values of the same size with the two matrix compared The return value is true if the relation between corresponding matrix elements holds and false otherwise.

Relational operator Description

< Less than

<= Less than or equal to

> Greater than

>= Greater than or equal to

== Equal to

~= Not equal to

The two matrices obviously have to be of equal dimensions and the operators are applied to pairs of corresponding elements of the two operands. If one of the operands is a single numerical value and the other is a matrix, the operators will apply as if the numerical value were a matrix of the same dimension with the other operand having all elements equal to the numerical value.

For example, >> a = [1 2; 3 4]

a =

1 2

3 4

>> b = [1 3; 5 7]

b =

1 3

5 7

>> a<b

ans =

0 1

1 1

Here 0 and 1 are logical 0 and 1, that is false and true. >> a = [1 2 3 4 5]; b = 3;

>> a > b

ans =

0 0 0 1 1

2.2. Logical operators

MATLAB offers the usual logical operators: and, or, negation , xor

From the way these operators are applied to the involved operands we can distinguish:

• Element-wise logical operators: &, |, ~ and xor

• Bit-wise logical operators: bitand, bitor, bitcmp, bitxor

Page 26: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

26 Michaelmas 2008

2.3. Logical indexing

Vectors of logical values offer an alternative method for matrix indexing. The indexing we have

been using so far is numeric: an index for the row and column was supplied. Logical indexing is

positional: it uses matrices of logical 0 and 1 and it is the position of each 1 in the logical matrix

that determines which array element is being accessed. Note that the 0 and 1 have to be logical

values, i.e. the result of either a relational or logical operator, or of a conversion from numeric

using the logical function.

For example, assume we have >> a = [1 2 3 4 5];

and we want to display the third and the fourth elements. We can do this with numerical

indexing: >> a([3 4])

ans =

3 4

To obtain the same result with logical indexing we use >> a(logical([0 0 1 10]))

2.4. Flow control

Normally, the series of commands in an M-file are executed in the order they appear. To alter the order in which the commands are executed, MATLAB provides the following flow control statements:

• if-else

• switch

• for

• while • break

• return

2.4.1. if-else statement

The if-else statement chooses between two sets of statements based on the evaluation of a logical expession. The general syntax of the this statement is

if <logical-expression>

<statement set 1>

else

<statement set 2>

end

When reaching this statement, MATLAB evaluates the logical expression and if it holds, then it executes the first set of statements, otherwise it executes the second set of statements. The else branch can be omitted, but it is compulsory for each if to be matched by and end to delimit its scope.

For example: function comparison(a,b)

if(a>b)

disp('First argument is the largest');

else

disp('Second argument is the largest');

end

called from the command line: >> comparison(2,3)

Second argument is the largest

Page 27: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 27

2.4.2. switch statement

The switch statement makes a choice between a series of statements, based on the value of a variable or expression. The general syntax is:

switch <variable/expression>

case <value 1>

<statement set 1>

.

.

case <value n>

<statement set n>

otherwise

<statements set n+1>

end

As for the if statement, the switch has to be matched by an end. For those familiar with programming in C the switch statement in MATLAB, unlike the C counterparts, does not “fall-through”, that is only the series of commands corresponding to matched case is executed, subsequent matching case statements are skipped.

For example function switch_example(error_code)

switch(error_code)

case 1,

disp('Level 1 error');

case 2,

disp('Level 2 error');

case 2,

disp('Level 3 error');

otherwise

disp('Unknown error code')

end

which called from the command line with 2 as input argument gives: >> switch_example(2)

Level 2 error

2.4.3. for statement

The for statement forces the execution of series of command a specified number of times. The general syntax is:

for <variable> = <expression>

<statement set> end

In practice, <expression> is most of the times in the form of a command for building an array, that is <start_value>:<step>:<start_value>.

For example, function s = for_example()

s = 0;

for i=1:1.5:4.5,

s = s + i;

end

will produce >> s

s = 7.5000

Page 28: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

28 Michaelmas 2008

2.4.4. while statement

The while statement forces the execution of a series of commands repeatedly as long as a certain logical expression holds. Its syntax is:

while <expression>

<statement set> end

The example with the for statement can be re-written using a while loop: function s = while_example()

s = 0;

i = 1;

while i<=4.5,

s = s + i;

i = i+1.5;

end

2.4.5. break, and return statements

break is used inside a for or while loop to force the immediate exit from the loop, regardless of the state of the controlling expression.

For example function a = break_example()

a = [];

for i=1:1.5:10,

a = [a i];

if(length(a)>4)

break

end

end

disp('Only 5 elements added');

will return Only 5 elements added

ans =

1.0000 2.5000 4.0000 5.5000 7.0000 return causes the immediate termination of the function. For example, the above can be re-written as:

function a = return_example()

a = [];

for i=1:1.5:10,

a = [a i];

if(length(a)>4)

return

end

end

disp('Only 5 elements added');

• In this case the 5 elements will be added, but the message will not be printed because return not only exits the loop, but also exits the function.

2.5. String evaluation: eval and feval functions

The eval(str) function allows the programmer to make the MATLAB interpreter execute a command stored in the str string variable.

For example, let’s consider the trivial task of adding two numbers and storing the result into a third variable:

>> a = 2; b = 3;

>> c =a+b

c =

5

Consider now that we build a string str to contain 'a+b':

Page 29: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 29

>> a = 2; b = 3;

>> str = 'a+b';

Echoing the string str will give: >> str

str =

a+b

We can now call the eval function with str as argument to execute the addition: >> eval(str)

ans =

5

The result of applying eval to str is 5, the sum of a and b. For another example, let’s remember how we initialise a matrix to have all elements zeros or ones:

>> seed1 = zeros(1,5)

seed1 =

0 0 0 0 0

>> seed2 = ones(1,5)

seed2 =

1 1 1 1 1

Assume now that as part of the initialisation for a function we either need to assign to seed variable all zeros or all ones, and that the initialisation function is passed as an input argument to the function. We can write the initialisation of seed using the eval function like this: function seed = eval_example(initFct)

theCommand = ['seed = ' initFct '(5,1);'];

eval(theCommand);

We can call the function with 'zeros' as input string: >> my_seed = eval_examples('zeros');

theCommand =

seed = zeros(1,5);

>> my_seed

my_seed =

0 0 0 0 0

Calling it with 'ones' as input string will give >> my_seed = eval_examples('ones');

theCommand =

seed = ones(1,5);

>> my_seed

my_seed =

1 1 1 1 1

feval function allows the execution of a MATLAB function whose name is supplied as an input: [outputarg1, …] = feval(fctname, inputarg1, …)

fctname is the name of the function to be executed, inputargs1,… are the function’s inputs and outputargs1,… are the functions outputs. For example, to achieve the same result as in the example given for eval function, we can use the following code:

function seed = feval_examples(initFct)

seed = feval(initFct, 1,5);

2.6. Useful functions

• find – returns indices and values of non-zero elements for a matrix

• all - tests a matrix to determine if all elements are nonzero

• any – tests for any non-zero values in a matrix

• isempty – tests for empty matrix

• isnan – tests for NaN

• exist - checks if variables or functions are defined logical - converts numeric values to logical

Page 30: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

30 Michaelmas 2008

2.7. Exercises

Exercise 10 Relational operators

Task 1 Comparing arrays

Step 1

Initialise two arrays: [ ]2 7 5 1 9a = − − and [ ]2 7 8 4 2b = − −

Step 2 Explain the result of the following operations:

• a>2

• a>b

• a==b

• (a >b) | (b >= a)

• (a > b) & (b >= a)

Task 2 Using array indexing

Step 1 Using a created in Task 1, Step 1, explain the output of a([0 1 0 0 0]) . What do you need to make it

work?

Step 2 Work out a way to display the negative values of an arbitrary array using a single command and logical indexing. Apply this to a.

Exercise 11 if-else and the for loop

Task 1 Building an array

Step 1 Using a for loop and array concatenation, write a function build_matrix(start, step, stop) to mimic the result of a = [start:step:stop]

Step 2 Use your function to create [0:0.01:1000]. Use the function cputime to compare the execution time of your function against the command a = [start:step:stop]

Task 2 Finding the extremes

Using a for loop, write a function to return the values and indices of the minimum and maximum for an

array of numerical data.

Task 3 Simple find function

Step 1 Using a for loop, write a function to return the index of the first occurrence of a certain number in a

numerical array. Ensure that the case of the element not being present is also dealt with (e.g. by returning -1, a value that is not a valid array index). Build suitable test cases to verify your function. Use the break command to prevent your function looping through the rest of the vector after finding the

first occurrence.

Step 2 Using a for loop, write a function to return the indices of all the occurrences of a certain number in a numerical array. Test the result of your function against the MATLAB’s built-in function find.

Task 4 Multiplying arrays

Step 1

Using a for loop implement the element-wise product of two arrays a and b : i i ic a b= . Test your

function against the result given by the .* operator.

Step 2

Using a for loop implement the dot-product of two arrays a and b of dimension n :

1

n

i i

i

c a b=

=∑ .

Test your function against the result given by the * operator.

Exercise 12 if-else and the while loop

Task 1 Simple find function

again

Using this time a while loop, re-write the function to return the index of the first occurrence of a certain number in a numerical array. Ensure that the case of the element not being present is also dealt with (e.g. by returning -1, a value that is not a valid array index). Test your function.

Page 31: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 31

Exercise 13 The switch statement and return

Task 1

In this exercise you will combine all the functions written for this session in one function session2. This function will have 2 input arguments:

• The first argument specifies the action that session2 will perform. You can specify the action as you find fit (with numbers, string, e.g. ‘build array’, etc).

• The second argument will be a matrix whose content will depend upon the action required: o For building an array will be a 1x3 array containing the start, step and stop values; o For the implementations of find will be an array containing the number to find as

first element, followed by the array to search; o For the two vector products, it will be a 2-row matrix containing the vector to

multiply; Use switch to select the appropriate function. Also implement checks on the validity of the second argument in relation to the action required. The function will display an error message and will return in case of invalid inputs.

Exercise 14 Choosing the flow control method

Task 1 Sorting an array

Write a function to sort a numerical array into ascending order. Check the result of your function against the MATLAB’s sort function.

Exercise 15 String evaluation

Task 1

Simple sum

Step 1 Clear the workspace. Load the file Exercise8_input_data.mat. Use who to see what variables have

been added to the workspace. You should see 5 variables called varsNN.

Compute the sum of all variables by adding one at a time, e.g. starting with s on 0, then s=s+var1;

s=s+vars11; etc.

Step 2

Use who to get the names of the variables added to the workspace into a cell array vars. vars should be a cell array with 5 elements:

vars =

'var1'

'var11'

'var23'

'var3'

'var30'

Step 3

Assume you don’t know the names of the variables, but you have them stored in the cell array vars. Using

vars, re-write the code for adding them up in a for loop using the eval function. Hint: you should evaluate iteratively a string built like this

['s=s+' vars{i} ‘;’].

Page 32: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

32 Michaelmas 2008

3 Input/Output and graphics

3.1. Saving and loading the workspace

The variables in the workspace are lost when the MATLAB session is closed. All or a selection of variables can be saved on the disk using the save function:

• save - stores all workspace variables in binary format in matlab.mat in the current directory

• save(<filename>) – the same as save on its own, only that the output file will be the one specified

• save(<filename>, <var1>, <var2>, ...) – saves in binary formaty only a selection of the workspace variables in a specified file

• save(<filename>, <var1>, <var2>, ..., <format>) - the same as above except that the format in which the data is saved is also specified (e.g. ‘-ascii’)

Saving all the variable in the workspace can also be done with Fi le |Save Workspace as Fi le |Save Workspace as Fi le |Save Workspace as Fi le |Save Workspace as from the MATLAB menu.

Variables stored on the disk with save can be retrieved using load:

• load – loads all the variables stored in matlab.mat (if this exists) in the local directory • load(<filename>) – the same as load on its own, only that the filename will be the one

specified

• load(<filename>, <var1>, <var2>,…) – loads only a selection of variables from the specified file For examples, the following session of MATLAB save the two variables a and b into first_matfile.mat: >> a = 2;

>> b = 3;

>> save('first_matfile.mat','a','b')

If we then delete a and b from the workspace with >> clear a b

we can bring them back to the workspace with >> load('first_matfile.mat')

3.2. Low-level I/O

MATLAB also supports low-level file I/O based on the ANSI C standard library:

• the files are opened and closed with fopen and fclose, respectively. fopen returns a file identifier, that needs to be then passed to the low-level I/O routines that deal with that file

• ascii files are read line by line with fgetl and fgets

• ascii files are saved and read with fprintf and fscanf

• binary files are saved and read with fwrite and fread

Descriptions:

• fid = fopen(<filename>, <mode>) - opens <filename> in the specified access mode, retuning the file identifier (which needs to be then passed to the low-level I/O routines that deal with that file); possible file access modes are:

o 'r' - reading (default) o 'w'- open or create file for writing, deleting existing contents, if any o 'a' - open or create file for writing, appending data to the end of the file o 'r+' - open file for reading and writing o 'w+' – open or create file for reading and writing, discarding existing contents,

if any. o 'a+' – open or create file for reading and writing, appending data to the end of

the file

Page 33: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 33

• fclose(fid) – closes the file whose file identifier is fid; a very useful variant is fclose('all') which closes all previously opened files

• tline = fgetl(fid) – reads a line from fid without the newline character

• tline = fgets(fid) – reads a line from fid including the newline character

• [A,count] = fscanf(fid,<format>,<size>) - reads the amount of data specified by <size>, converts it according to the specified <format> , and returns it along with a count of elements successfully read; possible options for <size>

o n - reads n elements into a column vector o inf - reads to the end of the file, resulting in a column vector containing the same

number of elements as are in the file o [m,n] - reads enough elements to fill an m-by-n matrix, filling the matrix in

column orders (n can be specified as inf, but m cannot)

• count = fprintf(fid,<format>,M,...) – writes into the file associated with fid the matrix M in the format specified format by <format>.

The format string contains C language conversion specifications. The conversion string has to start with % character and contain a string conversion character. Optionally, it may also contain various flags and fields specifying the width and precision. For example,

function m = fprintf_example()

a = [1.5 2.7 3.1 4.0];

fid = fopen('first_file.dat', 'w');

fprintf(fid, '%5.3f ', a);

fclose(fid)

writes in first_file.dat file the following 1.500 2.700 3.100 4.000

Changing the writing command to fprintf(fid, '%e ', a); will write in the file 1.500000e+000 2.700000e+000 3.100000e+000 4.000000e+000

Similarly, if we have a file containing

1 2 3

4 5 6

7 8 9

we can read the contents of the file into a matrix m with function fscanf_example()

fid = fopen('file_to_read.dat', 'r');

m = fscanf(fid, '%f %f %f', [3 Inf]);

fclose(fid);

m = m';

We need to transpose the matrix we have read because fscanf fills the matrix column by column.

In addition to this, MATLAB also has an extensive collection of functions for importing and exporting data in a variety of formats, among which:

• text (ascii) data

• graphics data (gif, jpeg, etc formats)

• audio/video data

• spreadsheets

3.3. Interfacing to formatted ASCII files

3.3.1. csvread/csvwrite functions

csvread function reads from ASCII files numerical data separated by commas. The general syntax of the function is:

M = csvread('filename', row, col, range)

Page 34: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

34 Michaelmas 2008

If row, col and range input arguments are not specified, the function will read the entire file, otherwise the function will start reading from (row, col) and will read only the range specified; range has to be given in the form [row_start col_start row_stop col_stop]. Note that the row/column and range specifiers are zero-based, that is for the first element in the file, row = 0 and col = 0.

For example, let’s assume we have the numerical values of our environmental data used in Section 1 in an ASCII file env_data_csv.dat containing:

18.1, 30.4, 210.1

20.3, 50.2, 250.8

17.1, 32.0, 220.3

10.5, 55.7, 190.2

To read the whole file we use

>> env_data = csvread('env_data_csv.dat')

ans =

18.1000 30.4000 210.1000

20.3000 50.2000 250.8000

17.1000 32.0000 220.3000

10.5000 55.7000 190.2000

If we only want to read the relative humidity and CO2 concentration from London, Birmingham and Glasgow, we use:

>> env_data = csvread('env_data_csv.dat', 1, 1, [1 1 3 2])

ans =

50.2000 250.8000

32.0000 220.3000

55.7000 190.2000

We can also write a comma-separated numerical file using csvwrite:

csvwrite('filename',M,row,col)

csvwrite will write into the file specified the matrix M of numerical values. If row and col are specified, the writing into the destination file will start at (row, col). Again, row and col are zero-based indices.

For example, given m =

0.3420 0.2897 0.3412 0.5341 0.7271

6.1858 16.7699 11.3614 7.4083 14.0548

we can write the whole matrix into a file with: csvwrite('csvwrite_example_data.dat', m)

and csvwrite_example_data.dat will contain 0.34197,0.28973,0.34119,0.53408,0.72711

6.1858,16.77,11.361,7.4083,14.055

If we want to write the data starting in the destination file from the first line, third column we do this with: csvwrite('csvwrite_example_data.dat', m, 0,2)

and the file will now contain ,,0.34119,0.53408,0.72711

,,11.361,7.4083,14.055

Note that the elements skipped in the destination file are marked as empty fields.

3.3.2. dlmread/dlmwrite functions

dlmread/dlmwrite functions are more general than csvread/csvwrite: they make no assumption about the delimiter between the numerical fields, but allow the user to specify an ASCII character delimiter. In fact, the actual implementation of csvread/csvwrite uses dlmread/dlmwrite to achieve the data transfer.

Page 35: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 35

dlmread takes a filename, a delimiter and a range specifier and returns a matrix of data. The syntax is:

M = dlmread('filename', ‘delimiter’, range)

Everything that was said for csvread keeps for dlmread, only that now the user can specify the delimiter between the numerical fields.

For example, let’s assume that our environmental data is stored in env_data_dlm.dat in the following form

18.1; 30.4; 210.1

20.3; 50.2; 250.8

17.1; 32.0; 220.3

10.5; 55.7; 190.2

We can read this using: env_data = dlmread('env_data_dlm.dat', ';');

A tab delimiter is specified \t. dlmwrite writes numerical data from a matrix into a file with a user-specified ASCII delimiter:

dlmwrite('filename', M, 'delimiter', R, C)

Again, what was said for csvwrite is also valid for dlmwrite.

3.3.3. textread function

textread function reads data from a formatted text file, assigning the output to multiple variables. The general syntax is:

[A,B,C,...] = textread('filename','format',N)

The format string determines the number and type of the return arguments. It supports a subset of the conversion specifiers and conventions of the C language fscanf routine – the help page for textread gives a table with the supported format specifiers.

Let’s assume we want to read from env_data_textread.dat file our environmental data stored as:

Oxford 12-Oct-05 18.1 30.4 210.1

London 10-Oct-05 20.3 50.2 250.8

Birmingham 15-Oct-05 17.1 32.0 220.3

Glasgow 02-Oct-05 10.5 55.7 190.2

We do this using

[lct dts tps hms co2] = textread('env_data_textread.dat', '%s %s %f %f %f')

which will generate lct =

'Oxford'

'London'

'Birmingham'

'Glasgow'

dts =

'12-Oct-05'

'10-Oct-05'

'15-Oct-05'

'02-10-05'

tps =

18.1000

20.3000

17.1000

10.5000

hms =

Page 36: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

36 Michaelmas 2008

30.4000

50.2000

32.0000

55.7000

co2 =

210.1000

250.8000

220.3000

190.2000 If our data is stored in the file including descriptions:

Location: Oxford Date: 12-Oct-05 Temperature: 18 Humidity: 30 co2: 210

Location: London Date: 10-Oct-05 Temperature: 20 Humidity: 50 co2: 250

Location: Birmingham Date: 15-Oct-05 Temperature: 17 Humidity: 32 co2: 220 Location: Glasgow Date: 02-10-05 Temperature: 10 Humidity: 55 co2: 190

we can read only the relevant alpha-numerical information as above, by specifying textread which characters to ignore by not preceding then with % character:

[lct dts tps hms co2] = textread('env_data_textread_extra.dat',...

'Location: %s Date: %s Temperature: %f Humidity: %f co2: %f')

3.4. Interfacing with Excel files

MATLAB has support for interacting with Microsoft Excel files. The way this interaction is handled has been changed from version 6 to version 7 of MATLAB. This course material presents the corresponding functions as they are implemented in MATLAB version 7.

xlsfinfo checks whether a file is in Microsoft Excel format (.xls) and returns a cell array with the names of the sheets in the file.

For example, if our environmental data is stored in an Excel file env_data_xls.xls in a sheet called autumn_data, then checking this file with xlsfinfo will give:

>> [type sheets] = xlsfinfo('env_data_xls.xls')

type =

Microsoft Excel Spreadsheet

sheets =

'autumn_data'

Data from Excel spreadsheets are read into MATLAB using xlsread function:

Assume now that our data is stored in env_data_xls.xls like this:

We can input the data into a MATLAB matrix using

>> env_data = xlsread('env_data_xls_00.xls')

This will produce

env_data =

18.1000 30.4000 210.1000

Page 37: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 37

20.3000 50.2000 250.8000

17.1000 32.0000 220.3000

10.5000 55.7000 190.2000

If out spreadsheet contains a line at the top with column labels like this:

and we read it with the same command, we’ll get the same result in the numerical matrix.

Now let’s add a column with the location and one with the dates for the data collection, such that our excel sheet will look like this:

If we now want to read both the numerical data (including the dates) and the text, we use: >> [env_data txts] = xlsread('env_data_xls_02.xls') which will return

env_data =

18.1000 30.4000 210.1000

20.3000 50.2000 250.8000

17.1000 32.0000 220.3000

10.5000 55.7000 190.2000

txts =

'Location' 'Date' 'Temperature' 'Humidity' 'CO2 concentration'

‘Oxford' '12/10/2005' '' '' ''

'London' '10/10/2005' '' '' ''

‘Birmingham ' '15/10/2005' '' '' '' 'Glasgow' '02/10/2005' '' '' ''

xlsread returns in txts the text contained in the spreadsheet as a cell matrix; in this case the first row and first and second columns of the matrix contain strings, the rest of the cells are empty, because the corresponding positions in the spreadsheet contain numerical values.

If the spreadsheet contains a text alongside with numerical values in a row (or column), xls read will put NaN in the corresponding locations of the numerical matrix returned. For example, if our spreadsheet looks like this:

>> [env_data txts] = xlsread('env_data_xls_03.xls')

Page 38: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

38 Michaelmas 2008

env_data =

18.1000 30.4000 210.1000 20.3000 50.2000 250.8000

17.1000 NaN 220.3000 10.5000 55.7000 NaN

txts = 'Location' 'Date' 'Temperature' 'Humidity' 'CO2 concentration'

'Oxford' '12/10/2005' '' '' '' 'London' '10/10/2005' '' '' ''

'Birmingham ' '15/10/2005' '' 'no data' '' 'Glasgow' '02/10/2005' '' '' 'no data'

Care should be taken to ensure that NaN values are not used in subsequent processing. From Release 14, MATLAB has the ability to export data into spreadsheet format with xlswrite function: xlswrite('filename', M, sheet, range)

which will write matrix M (or a range of values from M specified by range) into excel file 'filename', into sheet. The range specifies the point in the sheet to start writing the data; the syntax is ColRow (e.g. A2, B2, etc). If range is not specified, then the writing starts at A1. For example, let’s consider the following matrix: >> d = [1.2 2.3 4.5; 6.7 7.8 8.9;...

10.11 11.12 12.13; 13.14 14.15 15.16; 16.17 17.18 18.19]

d =

1.2000 2.3000 4.5000

6.7000 7.8000 8.9000

10.1100 11.1200 12.1300

13.1400 14.1500 15.1600

16.1700 17.1800 18.1900

We can write this data in a spreadsheet with >> xlswrite('xls_write_example_01.xls',d);

and the resulting spreadsheet will look like this:

As we have not specified any sheet to write into, it defaulted to writing to Sheet 1. We can export the matrix into sheet New data with

>> xlswrite('xls_write_example_02.xls',d, 'New data');

Warning: Added specified worksheet.

In xlswrite>activate_sheet at 254

In xlswrite at 212

In xlswrite_examples at 6

The data from d has been added to a new sheet MATLAB created (as the warning given when executing the command says) and the resulting spreadsheet looks like this:

Page 39: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 39

3.5. Graphics

3.5.1. Basics

MATLAB offers a wealth of tools for the graphical presentation of data, from basic line plots, as well to graphs like histograms, pie charts and contour plots. The graphs can be then annotated with titles, axes labels, legends, etc. Graphs created can then be exported to files in standard formats. plot(x, y, <line_spec>) – produces a 2D plot of x versus y using the line style

specified by <line_spec> . The <line_spec> is a string defining the line defining the colour, line and marker type. The following table gives some of the available options for these:

Colour Line type Marker type

'r' – red '-' – solid line '+' - plus sign

'g' – green '--' – dashed line 'o' - circle

'b' – blue ': ' – doted line '*' - asterisk

'c' – cyan '-.' – dash-dot line '.' - point

'm' – magenta 'x'- cross

'Y' – yellow 's' - square

'k' – black 'd' - diamond

'w' – white '^' - upward-pointing triangle

and more…

If the first argument x is not specified, the x-axis will represent the array indices.

For example, the following MATLAB sequence >> t = [0:2*pi/20:2*pi];

>> plot(t, sin(t), 'r:*');

produces a graph with red dotted plot with asterisk markers:

0 1 2 3 4 5 6-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

,

whereas plot(sin(t), ‘r:*’) will produce

Page 40: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

40 Michaelmas 2008

2 4 6 8 10 12 14 16 18 20-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

3D plots are produced in a similar fashion with:

plot3(x, y, z, <line_spec>) For example >> plot3(t, sin(t), cos(t), 'r:*')

generates

0

2

4

6

8

-1

-0.5

0

0.5

1

-1

-0.5

0

0.5

1

If more than one line plot is required in the same axes, this can be done in two ways

• using the hold function, which specifies whether new plots are added to the existing ones (hold on) or replace the already existing ones (hold off)

• specify more than one pair of x and y data in the same plot command

For example, >> plot(t, sin(t), 'r:*', t, cos(t), 'b-d')

has the same effect as >> plot(t, sin(t), 'r:*'); >> hold on

>> plot(t, cos(t), 'b-d'); When hold in set to on, all subsequent plots are added to the existing ones. Clearing of the current figure and is done using the function clf.

The graphs generated can be customized by adding grids and legends, altering/controlling the axis, adding axis labels and titles:

• grid on – adds grid lines

• axis tight - sets the axis limits to the range of the data

• axis equal - sets the aspect ratio so that the data units are the same along the x and y axis

• axis off - turns off all axis lines, tick marks, and labels

• legend(<txt1>, <txt2>,...) - displays a legend in the current axes using the specified strings to label each set of data.

• axis([0 1 -1 1 ] - sets the limits for x axes to 0 and 1 and for y axes to -1 and 2 • xlabel(<txt>) – adds the <txt> as label to the x axes

Page 41: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 41

• ylabel(<txt>) – adds the <txt> as label to the y axes • title(<txt>) – displays <txt> at the top of the current axes. • text(x,y,<txt>) – displays <txt> in the current axis at the location specified by

the x and y

For example the following MATLAB session >> plot(t, sin(t), 'r:*', t, cos(t), 'b-d'); grid on; axis tight;

>> xlabel('t'); ylabel('Function');

>> legend(['sin';'cos']);

>> title('Plot');

generates

0 1 2 3 4 5 6-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

t

Function

Plot

s in

cos

As seen, the plots done with plot have linear scales for both axes. For plots with (semi)logarithmic scales use

• loglog – the same as plot, only that both axes will have log scales

• semilogx and semilogy – the scale for x and y axes, respectively, will be logarithmic Histograms and pie charts can also be produced:

• hist(y, x) – draws the distribution of y among length(x) bins with centers specified by the elements of x

• pie(x) – draws a pie chart using the data in x. Mathematical symbols and/or text formatting (e.g. bold, newlines etc) can be added to the axis labels, title, legend using latex notation. For example the previous plot can be re-formatted with

>> xlabel('0\leq t\leq\pi'); ylabel('Function');

>> title('Plots of a {\bf sine} and {\bf cosine} function\newlinefor o\leq t\leq\pi')

to look like this

0 1 2 3 4 5 6-1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

0≤ t≤2π

Function

Plots of a sine and cosine function

for o≤ t≤2π

sin

cos

Page 42: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

42 Michaelmas 2008

Using File|SaveFile|SaveFile|SaveFile|Save from the figure menu will save the figure as a MATLAB function, which will generate the plot when invoked. Plots can be saved in various graphical formats using Fi le |Expor t. . .F i le |Expor t. . .F i le |Expor t. . .F i le |Expor t. . . , or using

print(-dformat, <filename>)

where –dformat specifies the graphics format – examples: -deps, -djpeg etc

Graphical output is displayed in MATLAB in figure objects; figure objects are created with the figure function, which most commonly takes the form figure(<n>) which makes figure numner

n the active figure object for subsequent graphical output (creating the object if it does not exist) or making it active if it already exists.

The subplot function creates and controls multiple axes in the same figure object. It is most commonly used in the form subplot(<m>,<n>,<p>) which creates an axes in the pth pane of a figure divided into an m-by-n matrix of rectangular panes.

For example, we can split the figure in two graphs arranged in rows:

function subplot_example()

t = [0:2*pi/20:2*pi];

figure(1); clf

subplot(211); plot(t, sin(t));

grid on; axis tight; title('{\bfsine} function');

subplot(212); plot(t, cos(t));

grid on; axis tight; title('{\bfcosine} function'); This function will produce the following figure:

0 1 2 3 4 5 6-1

-0.5

0

0.5

1sine function

0 1 2 3 4 5 6-1

-0.5

0

0.5

1cosine function

3.5.2. Working with graphics properties

Data visualisation in MATLAB is done using graphical objects. Each graphical object is created with a specific function that returns a numerical value called handle. The handle points to a structure that gives access to the properties of the graphical object. Graphical object properties are retrieved with get and are changed using set:

• get(h) – returns all properties of the graphics object identified by the handle h and their current values.

• set(h, PropertyName',PropertyValue,...) – sets the named properties to the specified values on the object identified by the handle h.

Graphics are displayed in graphical objects called figures. Figures are windows created with the figure function:

Page 43: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 43

• h = figure(n) – creates a figure and returns its graphics handle in h; if figure n already exists, it makes it visible, and raises it above all other figures on the screen; this figure is the target for subsequent graphics output.

Let’s now create a figure and get familiar with the figure properties.

>> hf = figure(1);

creates an empty figure and returns its handle in hf.

Using get we display the graphical properties of this figure:

>> fp = get(hf) fp =

Alphamap: [1x64 double]

BackingStore: 'on'

BeingDeleted: 'off' BusyAction: 'queue'

ButtonDownFcn: '' Children: [0x1 double] Clipping: 'on'

CloseRequestFcn: 'closereq'

Color: [0.8000 0.8000 0.8000] Colormap: [64x3 double]

CreateFcn: ''

CurrentAxes: []

CurrentCharacter: ''

CurrentObject: []

CurrentPoint: [0 0]

DeleteFcn: ''

DockControls: 'on'

DoubleBuffer: 'on'

FileName: '' FixedColors: [3x3 double]

HandleVisibility: 'on'

HitTest: 'on'

IntegerHandle: 'on'

Interruptible: 'on'

InvertHardcopy: 'on' KeyPressFcn: ''

MenuBar: 'figure'

MinColormap: 64

Name: ''

NextPlot: 'add' NumberTitle: 'on'

PaperOrientation: 'portrait'

PaperPosition: [0.6345 6.3452 20.3046 15.2284]

PaperPositionMode: 'manual'

PaperSize: [20.9840 29.6774]

PaperType: 'A4'

PaperUnits: 'centimeters'

Parent: 0

Pointer: 'arrow'

Page 44: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

44 Michaelmas 2008

PointerShapeCData: [16x16 double]

PointerShapeHotSpot: [1 1]

Position: [360 502 560 420]

Renderer: 'None'

RendererMode: 'auto' Resize: 'on'

ResizeFcn: ''

Selected: 'off'

SelectionHighlight: 'on'

SelectionType: 'normal'

ShareColors: 'on'

Tag: ''

ToolBar: 'auto'

Type: 'figure'

UIContextMenu: [] Units: 'pixels' UserData: []

Visible: 'on'

WindowButtonDownFcn: ''

WindowButtonMotionFcn: ''

WindowButtonUpFcn: ''

WindowStyle: 'normal'

WVisual: '00 (RGB 16 GDI, Bitmap, Window)'

VisualMode: 'auto'

Note: to make it easy to follow the discussion, the properties of interest in the text are italic underlined. This will apply to all subsequent discussions of graphical objects properties. We can see from the field Type that this graphical object is a figure, as we expected. Also, the figure is empty, as there are no children objects:

>> get(hf, 'Children')

ans =

Empty matrix: 0-by-1

The figure also has a menu bar at the top (MenuBar: 'figure'), a number title (NumberTitle: 'on') and no name (Name: ''). Also, the background colour is gray (Color: [0.8000 0.8000 0.8000]). Let’s assume we draw a simple plot of a sinusoid

>> t = [0:2*pi/20:2*pi];

>> hf = figure(1); clf

>> plot(t, sin(t), 'r:*', t, cos(t), 'b-d'); The result will be the creation of the following figure:

We can set the name of the figure >> set(hf, 'Name', 'Two plots figure')

which will change the figure to

Page 45: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 45

The following statement will get rid of the figure number in the figure name, will change the background colour to white and remove the menu bar: >> set(hf, 'NumberTitle', 'off', 'Color', [1 1 1], 'MenuBar', 'none');

and the figure will now be:

The ‘Figure properties’ section of the MATLAB help gives the full list of the figure properties and their acceptable values. After adding the plots to the figure, the figure properties changed. If we now investigate the Children field (which was an empty matrix before we added the plots) we get: >> get(hf, 'Children')

ans =

4.0402

which tells us that a child has been added to the figure. We can get information about this new graphical object using: >> get(get(hf, 'Children'))

which returns: ActivePositionProperty = outerposition

ALim = [0 1]

ALimMode = auto

AmbientLightColor = [1 1 1] Box = on

CameraPosition = [3.5 0 17.3205] CameraPositionMode = auto

Page 46: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

46 Michaelmas 2008

CameraTarget = [3.5 0 0]

CameraTargetMode = auto CameraUpVector = [0 1 0]

CameraUpVectorMode = auto CameraViewAngle = [6.60861]

CameraViewAngleMode = auto CLim = [0 1]

CLimMode = auto Color = [1 1 1]

CurrentPoint = [ (2 by 3) double array] ColorOrder = [ (7 by 3) double array]

DataAspectRatio = [3.5 1 1] DataAspectRatioMode = auto

DrawMode = normal FontAngle = normal

FontName = Helvetica

FontSize = [10]

FontUnits = points

FontWeight = normal

GridLineStyle = :

Layer = bottom

LineStyleOrder = -

LineWidth = [0.5] MinorGridLineStyle = :

NextPlot = replace OuterPosition = [0 0 1 1]

PlotBoxAspectRatio = [1 1 1] PlotBoxAspectRatioMode = auto

Projection = orthographic Position = [0.13 0.11 0.775 0.815]

TickLength = [0.01 0.025]

TickDir = in

TickDirMode = auto

TightInset = [0.0464286 0.0404762 0.00892857 0.0190476]

Title = [7.03833]

Units = normalized

View = [0 90]

XColor = [0 0 0]

XDir = normal

XGrid = off

XLabel = [8.03833]

XAxisLocation = bottom

XLim = [0 7]

XLimMode = auto

XMinorGrid = off

XMinorTick = off

XScale = linear

XTick = [ (1 by 8) double array]

XTickLabel =

0

1

2

3

4

5

6

7

XTickLabelMode = auto

XTickMode = auto

YColor = [0 0 0]

YDir = normal

YGrid = off

YLabel = [9.03833]

YAxisLocation = left YLim = [-1 1]

YLimMode = auto YMinorGrid = off

YMinorTick = off YScale = linear

YTick = [ (1 by 11) double array]

YTickLabel = [ (11 by 4) char array]

YTickLabelMode = auto

YTickMode = auto

ZColor = [0 0 0]

ZDir = normal

ZGrid = off

ZLabel = [10.0383]

ZLim = [-1 1]

Page 47: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 47

ZLimMode = auto ZMinorGrid = off

ZMinorTick = off ZScale = linear

ZTick = [-1 0 1] ZTickLabel =

ZTickLabelMode = auto ZTickMode = auto

BeingDeleted = off

ButtonDownFcn =

Children = [ (2 by 1) double array]

Clipping = on

CreateFcn =

DeleteFcn =

BusyAction = queue HandleVisibility = on

HitTest = on Interruptible = on

Parent = [1] Selected = off

SelectionHighlight = on Tag =

Type = axes

UIContextMenu = []

UserData = []

Visible = on The Type field of the structure returned indicates that we are having an axes object. Axes are graphical objects that define the coordinate system of each MATLAB graph. They are always part of a figure and contain the graphical objects that make up the graph. In our example, the axes are contained in Figure 1 and they contain the two plots. Axes properties can be manipulated in the same way as the figure properties to customize the graphical representation of the data. For example, from looking at these axes properties we can say that they have two children (Children = [ (2 by 1) double array]) – we’ll investigate later the children of axes - , the background colour is white (Color = [1 1 1]), there are no grid lines (XGrid = off and YGrid = off). Also we can see that there are 8 ticks along the x-axis with labels from 0 to 7 in steps of 1:

XTick = [ (1 by 8) double array] XTickLabel =

0 1

2 3

4 5

6 7

Let’s now change our figure to have horizontal grids (no vertical grids), with dashed lines. We achieve this with >> set(ha, 'YGrid','on', 'GridLineStyle', '--')

To put y-axis ticks and corresponding grid lines only at –1, -0.5, 0, 0.5 and 1 we use: >> set(ha, 'YTick', [-1 -0.5 0 0.5 1])

If we want the y-axis ticks to be labelled with some text rather than the actual numerical value we can use: >> set(ha, 'YTickLabels', {'Min', 'Half', 'Mean', 'Half', 'Max'})

After this series of statements, the figure will look like this:

Page 48: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

48 Michaelmas 2008

MATLAB has limited support for Latex notation for the title, xlabel, ylabel, legend functions. MATLAB has full support for Latex notation for the text function, provided that the ‘Interpreter’ field of the text object properties is set to ‘latex’. We can use the following series of statements to add text with mathematical symbols and formulas to our plot:

>> set(ha, 'YGrid','on', 'GridLineStyle', '--')

>> set(ha, 'YTick', [-1 -0.5 0 0.5 1])

>> set(ha, 'YTickLabel', {'-1', '', '0', '', 'MAX'})

>> text('Interpreter','latex',...

'String','$$\frac{1}{2}$$',...

'Position',[-0.3 0.5],...

'FontSize',10)

>> text('Interpreter','latex',...

'String','$$-\frac{1}{2}$$',...

'Position',[-0.3 -0.5],...

'FontSize',10)

>> set(ha, 'XTick', [0 pi/2 pi 3*pi/2 2*pi])

>> set(ha, 'XTickLabel', {'0', '', '', '', ''})

>> text('Interpreter','latex',...

'String','$$\frac{\pi}{2}$$',...

'Position',[pi/2 -1.1],...

'FontSize',10)

>> text('Interpreter','latex',...

'String','$$\pi$$',...

'Position',[pi -1.1],...

'FontSize',10)

>> text('Interpreter','latex',...

'String','$$\frac{3\pi}{2}$$',...

'Position',[3*pi/2 -1.1],...

'FontSize',10)

>> text('Interpreter','latex',...

'String','$$2\pi$$',...

'Position',[2*pi -1.1],...

'FontSize',10)

>> title('Plots of {\bf sine} and {\bf cosine} function with …0 \leq t \leq 2\pi')

The figure will now look like this:

Page 49: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 49

Let’s now investigate the children of the axes we have:

hp = get(ha, 'Children'); % the plots handle

for i=1:length(hp),

fprintf('hp %d type is: %s\n', i, get(hp(i), 'Type'));

end

The output of these statements will be: hp 1 type is: text

hp 2 type is: text

hp 3 type is: text

hp 4 type is: text

hp 5 type is: text

hp 6 type is: text

hp 7 type is: line

hp 8 type is: line There are 6 text objects and 2 line objects. The line objects are the sine and cosine we have plotted. Let’s have a look at the properties of one of the line objects: >> get(hp(5))

ans =

Color: [0 0 1]

EraseMode: 'normal'

LineStyle: '-'

LineWidth: 0.5000

Marker: 'diamond'

MarkerSize: 6

MarkerEdgeColor: 'auto'

MarkerFaceColor: 'none'

XData: [1x21 double]

YData: [1x21 double]

ZData: [1x0 double]

BeingDeleted: 'off'

ButtonDownFcn: []

Children: [0x1 double]

Clipping: 'on'

CreateFcn: []

DeleteFcn: []

BusyAction: 'queue'

HandleVisibility: 'on'

HitTest: 'on'

Interruptible: 'on'

Selected: 'off'

SelectionHighlight: 'on'

Tag: ''

Type: 'line'

UIContextMenu: []

Page 50: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

50 Michaelmas 2008

UserData: []

Visible: 'on'

Parent: 0.0090

DisplayName: ''

XDataMode: 'manual'

XDataSource: ''

YDataSource: ''

ZDataSource: ''

We can see that we have control upon many aspects of the plots appearance, e.g. line style/width/colour, marker type/size/colour etc. For example we can make the line thicker and change the marker to a yellow color with green edges:

set(hp(7), 'LineWidth', 3.0);

set(hp(7), 'MarkerSize', 10);

set(hp(7), 'MarkerFaceColor', 'yellow');

set(hp(7), 'MarkerEdgeColor', 'green');

The figure will now look like this:

A very useful function is axis. On its own, axis return the scaling for the current axis. For example, for the figure above it will return >> axis

ans =

0 6.2832 -1.0000 1.0000

axis([xmin xmax ymin ymax zmin zmax]) will set the current limits for the axes to the values specified. For a 2D plot the statement should be axis([xmin xmax ymin ymax]). axis tight sets the axis limits to the range of the data. See the help page for the full list of possible usages of the function. Figures can be saved into a special .fig using the hgsave funciton: hgsave('figure_handle','filename.fig')

.fig files can be re-loaded in MATLAB using: h = hgload('filename.fig')

Graphical objects can be exported into a wide variety of formats, e.g. eps, jpeg, tiff etc. This is done using the print function: print('-dformat' ,'filename')

Page 51: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 51

For example, to save the previous figure into a jpeg file we can use: print('-djpeg', 'my_first_plot.jpg’);

See the print help page for a full list of supported format.

3.5.3. Some 3D plots

A 3D surface is defined in MATLAB as the z coordinates above a x-y grid. Adjacent points are linked with straight lines.

For example, let’s plot the two-variable function 2(1 )sin( )z y xπ= − with x and y going from –1

to 1. First we need to create the x-y grid. This can be done with the meshgrid function: [X,Y] = meshgrid(x,y)

meshgrid transforms the domain specified by vectors x and y into matrices X and Y, which can be used to evaluate functions of two variables and three-dimensional mesh/surface plots. The rows of the output matrix X are copies of the vector x; columns of the output matrix Y are copies of the vector y. For example,

>> x = [1:2:5];

>> y = [11:2:15];

>> [X,Y] = meshgrid(x,y)

X =

1 3 5

1 3 5

1 3 5

Y =

11 11 11

13 13 13

15 15 15

We can now plot our two-dimensional function with mesh function [x,y] = meshgrid(-1:0.1:1);

z = (1-y.^2).*sin(pi*x);

figure(1); clf

mesh(x,y,z)

mesh produces a wireframe parametric surface with the colour proportional to surface height:

The mapping between the surface height and the colour of the mesh is controlled with the colormap function; there are a number of pre-defined colour maps, the default one being ‘jet’ – the above plot uses the default colour map. We can change the colour map to one of the pre-defined ones, for example after >> colormap(‘winter’)

our plot becomes

Page 52: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

52 Michaelmas 2008

The same function can be plotted to a three-dimensional shaded surface with: >> surf(x,y,z)

The result is:

colormap will act on the this surface in a similar way. By using colormap(‘winter’) the surface will become:

The colour shading of the surfaces is controlled with the shading function. Using shading(‘flat’) will change the above plot to:

Page 53: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 53

while shading(‘interp’) will produce

The colour scale of the plot (i.e. the correspondence between the values of the z and the colour of the corresponding points on the surface) can be displayed alongside with the plot using the colorbar function.

Page 54: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

54 Michaelmas 2008

We can see from the colour bar that z spans from –1 to 1, with the points with smaller values having colours towards blue and the points with higher values having colours towards red. If we want to compare two surfaces using their color bars it is useful to have the same coulour scaling. For example, if we plot the above surface alongside with a slightly modified one with

subplot(211); surf(x,y,1.5*z); shading('interp');

colorbar

subplot(212); surf(x,y,z); shading('interp');

colorbar

we obtain

The two surfaces have different scaling for the z axis, therefore, for example, dark red means 1.5 for the first plot and 1 for the second. We can make the two scalings equal with caxis:

subplot(211); surf(x,y,1.5*z); shading('interp');

first_axis = caxis;

colorbar

subplot(212); surf(x,y,z); shading('interp');

caxis(first_axis)

colorbar

to obtain:

Page 55: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 55

pcolor(x,y,z) draws a pseudocolor plot of the elements of y at the locations specified by x and z. The plot obtained will be like a projection on the xy plane of the surf plot. pcolor plots are also controlled by the colormap and shading functions. For example, if we consider the surface obtained with

[x,y] = meshgrid(0:0.05:1);

z = (1-y.^2).*sin(pi*x).*cos(pi*x+pi/2);

surf(x,y,z);

colormap('jet'); shading('flat');

colorbar

The pcolor plot of this surface generated with

pcolor(x,y,z); colormap('jet'); shading('flat');colorbar

xlabel('x axis'); ylabel('y axis');title('My plot')

will be

We can represent the isolines from a matrix using the contour function. For the above data, using contour(x,y,z); colorbar

we obtain

Page 56: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

56 Michaelmas 2008

The lines obtained can be labelled with clabel function. To achieve this, we first need to store the outputs of the contour function (contour matrix C and a handle to a contour group object) and to pass them to clabel. The following sequence

[C h] = contour(x,y,z); colorbar

clabel(C,h);

will produce

Three-dimensional plots can also be customized to have axis labels, grids, title. For example, applying the following on the above plot

xlabel('x axis'); ylabel('y axis'); zlabel('Function')

title('My plot') will produce

Page 57: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 57

3.6. Exercises

Exercise 16 Loading a workspace and plotting simple graphs

Task 1 Load a workspace

Step 1 Clear the current workspace. Load from the file smiley.mat from the disk.

Step 2 Study the content of the workspace after loading the file and follow the instructions hidden (not that well…) . Can you add other things to the final result to make it nicer?

Task 2 Plot in various axes

Step 1 Create an array x with values from 0 to 5 in steps of 0.1.

Step 2

Plot the function x , 5

x and 2x

e . Use ordinary , semi-logarithmic and logarithmic axis and compare

the results. You may like to make use of subplot function. Add titles and labels.

Exercise 17 Reading formatted files

Task 1 Extracting data from a file

Step 1 Open in the MATLAB editor the file called map.dat and study its content.

Step 2 Read in the cities’ locations, their names and the interconnections, ignoring the lines with comments.

Step 3 Plot the cities’ locations with circle markers and draw the links as per connections specified. Then add names to each city location. For this, use text in a for loop.

Exercise 18 Interfacing with character delimited files and reading text files into multiple outputs

Task 1 Reading a character delimited file

Step 1 Clear the workspace. Open Exercise5_input_data.dat into Notepad and study its content. You should see 4 lines of numerical value separated by semicolons.

Step 2 Import the data from Exercise5_input_data.dat in MATLAB into a matrix d using dlmread.

Check the data read with who: d should be a 4x48 numerical matrix.

Step 3 Plot in the same figure the rows in d (from the second to the last row) against the first row. Add a suitable legend to your plot. Hints:

• Use a for loop and hold on.

• To control the colour, marker and line style for each plot in your for loop, build a pattern array to pass on to the plot function. Example: pattern = {'r*-' 'b^:' 'mx-'};

and use in a plot function like this: plot(x,y, pattern{2})

to draw y versus x with blue dotted line and upward pointing triangle.

Task 2 Writing data into a character delimited file

Step 1 Write d excluding the first row into a tab delimited file.

Exercise 19 Reading text files into multiple variables

Task 1

Step 1 Clear the workspace. Open Exercise6_input_data.dat into Notepad and study its content. You should see 5 lines of alphanumerical characters. Each line contains a record for a person: name, University card number and affiliation within the University.

Step 2 Use textread to input the information from Exercise6_input_data.dat in MATLAB into three variables:

• A cell array for names • A numerical array for card numbers

• A cell array for affiliation

Page 58: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

58 Michaelmas 2008

Exercise 20 Interfacing with excel files

Task 1

Step 1 Clear the workspace. Open Exercise7_input_data.xls into Excel and study its content. The spreadsheet should have 3 sheets, each sheet specifying a location, a date and having two columns of data: time and measurements.

Step 2 Using xlsfinfo get into a variable sheets the names of the sheets in the given spreadsheet.

Step 3 Pass through sheets and import in MATLAB the text and numerical data stored in the given xls file.

Create a structure array to hold the data read, a structure for each sheet with the following fields: • Location

• Date

• Time • Measurement data

Step 4 Plot all the data in one figure with different patterns (use what you have learned in Exercise 5, Task 1).

Step 5 Pass through the structure array and build a cell array for the legend of the plot, which should state for each plot <sheet name>: <location>, <date>

Exercise 21 More plots

Task 1 3D coil

Step 1 Create an array t with value from 6π− to 6π in steps of 0.1. Create another array of amplitudes

2

0 1a a t= + with 0a being, for example 0.01.

Step 2

Draw the 3d plot of sina t and cosa t versus t. Use the function view to change the viewpoint of the plot.

Task 2 Simple data fitting

Step 1 Read the contents of the file polydata.dat. The first column of data represents time and the second column some experimental data. Plot the data against time. Note that the time is not ordered.

Step 2 Derive a polynomial model for the data using polyfit. Investigate polynomials of various order. Plot

both the data and the models obtained for visual comparison. Customize the plot (labels, grids, title, legend, etc) as if prepared for a publication.

Exercise 22 Even more plots

Task 1 Pie chart

Assume that during this MATLAB course you have spent 20% of the time listening to the lecturer, 50% editing, 10% testing and 10% using the help. Draw a pie chart of this data. Emphasize the time spent testing. Can you add labels to your chart?

Task 2 Histograms

Generate a histogram of 1000 randomly generated numbers between 0 and 1. Use both a normal and a uniform distribution. Make your histograms look smooth.

Page 59: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

Michaelmas 2008 59

Exercise 23 Customizing a 2D plot using graphics properties

Task 1

Step 1 Clear the workspace. Load Exercise9_input_data.mat; a structure array data with three elements has been added to your workspace. The elements have 4 fields: location (string), date (string), time (numerical array) and d(numerical array).

Step 2 Draw in the same axis plots of d versus time for all the elements in data. Use a for loop to do the plots and an array of patterns (as used

in Exercise1, Task 1 to distinguish between the plots. While passing through the structure array to do the plots, also build a cell array for the plot legend to specify for each plot: Experiment <ordinal_number>: <location>, <date> Add the legend to the plot in the upper right-hand side corner.

Step 3 Set the y axis to span from 0 to 5. Draw a horizontal blue dotted line at the mean for data(1).d. Assume that the safe minimum and maximum limits are 0.5 and 3.0, respectively. Draw red horizontal thick lines to mark these boundaries. To be able to access the lines properties the easiest way is to store the handle returned by the plot function.

Step 4 Get the handle for the axes (children of the figure object) and use set function to

• Set the ticks of the x axis only to 0, 3, 6, 9, 12, 15, 18, 21 and 24

• Set the ticks for the y axis only at 0, safe minimum limit, mean value for data(1).d, safe maximum limit and 5.

• Turn on only x grids with dotted lines

Step 5 Turn the number title off and add a title to the figure. Add a title to the plot spread it over two lines (using Latex sequence \newline)

Page 60: Introduction to MATLAB - University of Oxford...MSc in Mathematical and Computation Finance Introduction to MATLAB Michaelmas 2008 5 1.2.1. The environment An example of a working

MSc in Mathematical and Computation Finance Introduction to MATLAB

60 Michaelmas 2008

Task 2 Fit a model, plot it with the data and customize the plot

Step 1 Put all the time and d fields from Task 1 together into alltime and

alld, respectively. Plot the data without interconnecting lines, only points where there is experimental data.

Step 2 Fit a third order polynomial model to the data and plot the model together with the experimental data. Customize the plot to look like this:

Note that the title has different font type and size from the rest, i.e. is TimesNewRoman, 15 points. The default font is Helvetica 10 ppoints. The title was produced making use of the Latex notation. Make your code capable or handling any model order, not just 3.

Step 3 Save your plot in .fig .jpeg and .eps formats. Try and re-open your saved .fig file in MATLAB. Use another program to check your .jpeg and .eps file. Which one has the best image quality? Use the help for print to see how you can change the resolution of your saved file.

Exercise 24 3D plots

Task 1

Step 1 Open in MATLAB editor Exercise10.m. It contains a piece of code

that builds two slightly different surfaces. Use these surfaces to explore the 3D plots discussed in this Session. You may like to try mesh, surf, contour, pcolor, explore the colormaps and the interpolation choices, add labels, title, text etc. You may like to compare the two surfaces also making use of caxis to use the same scale for axis for both surfaces. Also, you may like to try and add a title to the plot containing the mathematical formula of the surface using Latex notation.