You are on page 1of 153

Financial Modelling with MATLAB

Part 1

EDHEC 2015, version: 1.5, author: Ian Hunt


CONTENTS

Contents
1 Basics 8
1.1 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2 Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3 MATLAB as a Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.4 Calculation Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.5 Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.6 NaN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.7 Appearance of Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.8 Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.9 Strings and Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.10 String Searches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.11 String Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.12 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.13 Printing something to the screen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
1.14 HELP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.15 Creating MATLAB variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.16 Simple Numerical Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
1.17 Deleting Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.18 Naming and Overwriting Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.19 Entering multiple statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
1.20 Suppressing Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.21 Special Structure Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
1.22 The Best Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

2 File Structures 36
2.1 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

EDHEC 2015: MATLAB Part 1 2


CONTENTS

2.2 Directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.3 Current Folder and Others . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.4 Scripts and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
2.5 Data Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
2.6 Link to Microsoft EXCEL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2.7 Link to Plain Input/Output Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
2.8 Chart Files - MATLAB Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
2.9 Chart Files - Generic Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
2.10 Toolboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

3 Matrices 49
3.1 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
3.2 Creating Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
3.3 Matrix Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
3.4 Re-shaping a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.5 Referencing the data that you want . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.6 Logical Referencing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.7 Data Generation Tricks - Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
3.8 Data Generation Tricks - Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
3.9 Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
3.10 Referencing Cell Array Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
3.11 A “Matrix” of Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
3.12 Applying Functions to Each Element of a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
3.13 Applying Functions to Each Element of a Cell Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

4 Control Structures 64
4.1 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
4.2 FOR Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

EDHEC 2015: MATLAB Part 1 3


CONTENTS

4.3 WHILE Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67


4.4 IF Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
4.5 ELSEIF Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
4.6 Nesting Loops and Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
4.7 Vectorisation vs. Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
4.8 Other . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

5 “Random” Numbers 73
5.1 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
5.2 Generating Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.3 Other Useful Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
5.4 Setting the “Seed” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

6 Matrix Algebra 79
6.1 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6.2 Element-by-Element Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.3 Element-by-Element Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
6.4 Advanced Element-by-Element Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
6.5 Proper Matrix Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.6 What is going on? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
6.7 Transpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.8 More Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

7 Relations and Logic 91


7.1 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
7.2 Relations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
7.3 Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
7.4 Matrix Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

EDHEC 2015: MATLAB Part 1 4


CONTENTS

7.5 True or False . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96


7.6 Logical Referencing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
7.7 Example: Missing Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
7.8 More Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100

8 Functions 101
8.1 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
8.2 MATLAB functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
8.3 Functions are Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
8.4 A Test Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
8.5 A Test Function with Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
8.6 Functions with Multiple Inputs and Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
8.7 Order Matters for Inputs and Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
8.8 Order Matters Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
8.9 Function Rules-of-Thumb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
8.10 Optional Parameters to Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
8.11 Anonymous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
8.12 Anonymous Functions From Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
8.13 Sub-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
8.14 More Complex Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

9 Optimisation 116
9.1 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
9.2 Optimising What? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
9.3 MATLAB Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
9.4 Technical Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
9.5 Typical Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
9.6 Routine Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

EDHEC 2015: MATLAB Part 1 5


CONTENTS

9.7 Three Useful MATLAB Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123


9.8 Simple Optimisation Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
9.9 More Complex Optimisation 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
9.10 More Complex Optimisation 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
9.11 Older Versions of MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
9.12 Quadratic Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
9.13 Quadratic Example Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

10 Basic Charts 130


10.1 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
10.2 Basic Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
10.3 Titles and Labels etc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
10.4 Multiple Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
10.5 Saving and Deleting Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
10.6 Multi-charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
10.7 Basic Chart Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
10.8 Multiple Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

11 Scripts 139
11.1 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
11.2 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
11.3 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
11.4 Variable Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
11.5 Planning a Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
11.6 Miscellaneous Advice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

12 Basic Probability 147


12.1 Goal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

EDHEC 2015: MATLAB Part 1 6


CONTENTS

12.2 Probability Distributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

13 Extensions 150

EDHEC 2015: MATLAB Part 1 7


Basics

1 Basics

EDHEC 2015: MATLAB Part 1 8


Basics

1.1 Goal

The goal of this first section is to teach the first steps.

• How to start MATLAB.


• Do a few simple calculations.
• Understand the breadth and power of the MATLAB programming language.

EDHEC 2015: MATLAB Part 1 9


Basics

1.2 Environment

We work with several different windows.

• Command Window (where the action is).


• Workspace (a listing of objects that you have created).
• Command History (what you have done so far, including mistakes).
• Directories (where things get saved and retrieved).

EDHEC 2015: MATLAB Part 1 10


Basics

EDHEC 2015: MATLAB Part 1 11


Basics

1.3 MATLAB as a Calculator

You just need to type the expression that you want to evaluate. For example, sup-
pose you want to calculate 1 + 2 ∗ 3. You simply type it in at the Command Window
prompt (“EDU>>” or “>>” if you have a full licence) as follows,
1+2*3
.

EDHEC 2015: MATLAB Part 1 12


Basics

1.4 Calculation Order

Be sure to use round brackets to get the order of calculation as you require.
(1+2)*3
1+(2*3)
.

EDHEC 2015: MATLAB Part 1 13


Basics

1.5 Sequences

The operator colon (“:”) is a convenient way to produce sequences. With just
two numbers, say x:y, a sequence between x and y is returned. If you use three
numbers, say x:y:z, then a sequence between x and z is returned where the steps
are of size y (watch out for truncation if the steps do not evenly make it all the way
to z).
For example
1:10
1:2:10
10:-2:-10
.
You will use this a lot in your MATLAB applications.

EDHEC 2015: MATLAB Part 1 14


Basics

1.6 NaN

MATLAB uses the placeholder NaN for missing values, which often occur in financial
time series.
NaN
NaN + 1
NaN * 100
.

EDHEC 2015: MATLAB Part 1 15


Basics

1.7 Appearance of Numbers

The default display of numbers, in terms of decimal places, can be set to format
short or format long. Compare
format short
100.000001
.
and
format long
100.000001
.
There are other number formats in MATLAB, but these two will suffice for our course.

EDHEC 2015: MATLAB Part 1 16


Basics

1.8 Dates

Dates are tricky: precise syntax and formats are required (that goes for any pro-
gramming language).
Dates in MATLAB can be stored as either numbers or strings. The applicable func-
tions are datestr and datenum. For example
x='2001-12-31'; % ISO format
datestr(x,'dd-mmm-yy') % change format
datenum(x,'yyyy-mm-dd') % MATLAB storage
.
It is important that the second part of datenum matches the format of the string
exactly.
We will stick to storing dates as strings, making conversions as required for out-
puts (many financial applications involve time series). Conversions are done first by
transferring a string to a MATLAB number and then re-formatting this number.
For example

EDHEC 2015: MATLAB Part 1 17


Basics

x='04/01/2001'; % Datastream date format


y=datenum(x,'dd/mm/yyyy') % note the syntax
datestr(y,'dd-mmm-yy')
.
Compare that to
x='04/01/2001';
y=datenum(x,'mm/dd/yyyy')
datestr(y,'dd-mmm-yy')
.

EDHEC 2015: MATLAB Part 1 18


Basics

1.9 Strings and Concatenation

The two main types of data in MATLAB are numeric (numbers) and strings (words,
if you like). Numbers are entered in an obvious fashion. Strings are entered by
surrounding a word by a single quote mark.
'a string'
.
There are many string manipulation functions in MATLAB, and handling them can
be more tricky than you might think. However, we will stick to two string manipula-
tions. First, concatenating (i.e. joining) strings using strcat. Secondly, converting
numbers to strings with num2str. For example
strcat('example','1','.xls')
strcat('example',num2str(1),'.xls')
.

EDHEC 2015: MATLAB Part 1 19


Basics

1.10 String Searches

MATLAB programming allows for extensive string operations. This may be of use
to some scientists, such as biologists and geneticists working on DNA codes. In
finance, strings only tend to be used to organise our data; this is still useful, for
example when we work with data matrices in which each column is a different asset.
The only string search function we will use is regexp, which searches for a specified
pattern within a string (regexpi is the same but case insensitive). If it finds one, or
more matches, then the indexed location of the first match is returned. Otherwise
nothing is returned.
regexp('hello','lo') % where does 'lo' occur in 'hello'
regexp('hello','x') % its not there (isempty(regexp('hello','x'))==1)
.

EDHEC 2015: MATLAB Part 1 20


Basics

There are many possible qualifications to string searches. We will only use “wild
card” (anything), .*, “must begin with”, ˆ, and “must end with”, $. For example

regexp('hello and goodbye','good') % good anywhere


regexp('hello and goodbye','^good') % starts with good
regexp('hello and goodbye','^h.*lo.*g.*y') % bits in order, anything between
regexp('hello and goodbye','^h.*lo.*g.*y$') % same but must end in y
regexp('hello and goodbye','^h.*e$') % begin with h, anything, end in e
.

EDHEC 2015: MATLAB Part 1 21


Basics

1.11 String Comparisons

Basic string comparisons are done with the command strcmp. If the strings are an
exact match then true is returned (which appears as “1” in the Command Window);
otherwise false is returned (which appears as “0” in the Command Window). For
example
strcmp('hello','hello again') % false
strcmp('hello','hello') % true
.

EDHEC 2015: MATLAB Part 1 22


Basics

1.12 Comments

You can and should provide many comments (explanations and notes) in your code.
This is so that you don’t get lost or waste your time when developing and revisiting
code. It also enables other people to understand and use your code.
Comments are made after typing “%”. For example
(1+2)*3 % this is a trivial calculation but important note
.
MATLAB ignores anything directly following the symbol % .

EDHEC 2015: MATLAB Part 1 23


Basics

1.13 Printing something to the screen

You can print something in the Command Window with fprintf. For example

fprintf('hello')
fprintf('hello\n hello again \n') % \n makes a new line
.
This method can also be used to print to files, but we will not be doing this.
The disp function uses up less space on the Command Window, which can be
handy. For example compare
'hello'
disp('hello')
.
Finally, use “format compact” to condense Command Window outputs (the default
is “format loose”).

EDHEC 2015: MATLAB Part 1 24


Basics

1.14 HELP

Use the help functions as much as you can. This is how you will learn and use
MATLAB properly; even advanced users look-up HELP frequently. There are three
main MATLAB help functions: help (for precise entries), lookfor (every time it is
mentioned) and doc (detailed manual). For example
help mean
lookfor mean
doc mean
.
The doc help is the best – and you can search within it via a search box for things
you cannot find directly (just type doc on its own to bring up the interface).
Also check the internet if you are stuck – http://stackoverflow.com articles are good
and Mathworks (the MATLAB makers) also have online help.

EDHEC 2015: MATLAB Part 1 25


Basics

1.15 Creating MATLAB variables

Variables are created by setting the name that you want equal to something (using
“=”). The “something” can be

• A typed-in entry (like some numbers or a matrix).


• The output from a MATLAB function.
• The output from a function that you have created.
• The contents of file, like a spreadsheet.

In this section we concentrate on the first type. The others will follow later (quite
quickly), but the all the same rules apply.

EDHEC 2015: MATLAB Part 1 26


Basics

1.16 Simple Numerical Variables

If you do not specify an output variable, then MATLAB uses a default variable call
ans, short for answer, to store the results of the current calculation.
1+2
ans
.
A default variable ans is created or overwritten every time something is entered
without being assigned a name. To make something permanent, you assign the
result to a variable. For example,
x = 1+2*3
.
This variable name can be used to refer to the results of the previous computations
and inputs. For example computing 4x can be done with
4*x
.
You can also assign this result to a new variable, y say:

EDHEC 2015: MATLAB Part 1 27


Basics

y=4*x
.
You can view all your variables by typing
who % a list
whos % more details
.
All objects can also be seen in Workspace window (and can be double-clicked).
Quitting MATLAB destroys all your objects. We will learn later how to save MATLAB
variables for later use, though it is best to simply save the code that generated them.

EDHEC 2015: MATLAB Part 1 28


Basics

1.17 Deleting Variables

You can delete all your variables by typing clear.


Use this carefully: there is no going back.
Using clear x y will delete only x and y.

EDHEC 2015: MATLAB Part 1 29


Basics

1.18 Naming and Overwriting Variables

You are the boss: MATLAB variables can be created at will. But they will be over-
written if you use the same name (you may desire this).
Be sure to use a sensible naming system. Some rules-of-thumb follow.

• You cannot have names with gaps in them.


• Don’t use punctuation or special characters (e.g. $ or !).
• Don’t start a name with a number.
• Use capitals where appropriate.
• Join name parts with “_” or capital letters.

EDHEC 2015: MATLAB Part 1 30


Basics

Finally, try very hard not to use reserved MATLAB words or existing functions (you
can check for existing names using which, though this is a bit vague).
% mean is a MATLAB function
mean([1 2 3])
which mean
mean=5
mean([1 2 3])

% so delete your object ...


clear mean
mean([1 2 3])
.
If your syntax is not exactly what MATLAB needs then you will get an error. This
means you need to try again ... You can use the “up” arrow key to restore previous
commands (also available in “Command History” window) in order to edit them
(press “return” to re-enter).

EDHEC 2015: MATLAB Part 1 31


Basics

1.19 Entering multiple statements

Use a comma (“,”) to join multiple lines of code together. For example
x=1 , y=2 , z=3
.
Use (“...”) to join multiple lines of code into one line. For example
x=1+2 ...
+ 3
.
x=1+2 ...
+ 3 ...
- 5 , y=2 , z=3
.

EDHEC 2015: MATLAB Part 1 32


Basics

1.20 Suppressing Output

Use a semicolon (“;”) to run a line of code but suppress any output. See the differ-
ence between
x=100*9
.
and
x=100*9;
.
A semicolon also allows you to run multiple lines of code on one line (without using
a comma as well).
x=1;y=2;
x=1,y=2
x=1,;y=2;
x=1;,y=2;
.

EDHEC 2015: MATLAB Part 1 33


Basics

1.21 Special Structure Variables

Structure variables can take multiple attributes. We will use these throughout our
course. First you define an object as a structure variable (sometimes this step can
be skipped, but it is best to always include it):
x=struct;
.
Then you can create and assign data to different attributes of the variable by using
a full-stop. For example
x.data=1:100;
x.name='somename';
x
.
These attributes can be different data types (e.g. string and numeric) and they can
be referenced and used as if they were separate objects. For example
x.name , x.data
.

EDHEC 2015: MATLAB Part 1 34


Basics

1.22 The Best Built-in Functions

There is a range of useful MATLAB functions that we will use a lot. These include
mean, var, max, min, abs, prod, cumprod, sum, cumsum, exp, log, sqrt , sign ...
They are all used in more-or-less obvious ways, except perhaps for the “cum” ex-
tensions.
sum(1:10)
cumsum(1:10)
.
Most functions like these can also be applied directly to rows or columns of matrices
if you specify the dimension (row=1, column=2).
x=[1,2;3,4] % a matrix -- see later sections
sum(x,1) , sum(x,2)
.
Always check HELP for details (e.g. doc sum) or if you are in doubt about how a
function works.

EDHEC 2015: MATLAB Part 1 35


File Structures

2 File Structures

EDHEC 2015: MATLAB Part 1 36


File Structures

2.1 Goal

In this section you will learn how to create and save files with MATLAB, including
files that

• Contain scripts and functions that run multiple commands (.m suffix)
• Store data (.mat, .xlsx and .csv)
• Contain charts (.fig and .png)

Perhaps most importantly, you will be able to read from and write to structured files
such as spreadsheets and comma-separated files.

EDHEC 2015: MATLAB Part 1 37


File Structures

2.2 Directories

It is easiest to use your MATLAB “Current Folder” to arrange your work. Find a main
directory and folder that you are happy with. You can always include folders using
the command addpath. For example
addpath 'C:\Users\All Users\Temp\'
.
which can be removed with
rmpath 'C:\Users\All Users\Temp'
.
Use the following command to see all folders that MATLAB is currently “looking at”

path
.

EDHEC 2015: MATLAB Part 1 38


File Structures

2.3 Current Folder and Others

You can see the Current Folder by typing pwd. Use cd to change it with code,
otherwise use the MATLAB Windows interface (GUI).
Setting up other folders and paths for assignments and organising your scripts and
functions can also be done via the GUI. For example in File –> Set Path and by
right-clicking the mouse on a file or folder in the Current Folder window and selecting
Add to Path or Remove from Path. We will go through this in class (we will try
get you some working folders that will load automatically each MATLAB is started).

EDHEC 2015: MATLAB Part 1 39


File Structures

2.4 Scripts and Functions

Scripts and functions are saved in .m files. Usually you write a number of functions,
each in their own files. Then you run a main script which builds variables, runs the
functions and outputs results. We will cover functions in a later section. Multiple
script files can also be run in sequence.
Variables inside functions stay inside functions. Variables in different scripts cross-
over. This is called scope (we will aim to keep these issues as simple as possible.)
To build a script file go to Windows extension File –> New –> Script. You will get
an Editor screen within which you can write multiple lines of code. These files can
be saved in the normal Windows fashion. The default directory for saving will be the
“Current Folder”.
To run a script press the green triangle in the centre-top commandbar (or press F5).
We will cover de-bugging scripts in class as it arises.
Assignments will primarily be based on building and submitting .m files. This is how
you will use MATLAB at work and in advanced academic research (i.e. your other
courses, MSc dissertation and any subsequent PhD work).

EDHEC 2015: MATLAB Part 1 40


File Structures

2.5 Data Files

Variables and data from a session can be saved in separate .mat files. You can
save all your objects or just those you want. By default the files will be saved in your
Current Folder. For example
x=1;,y=2;,z=3;
save ('test')
clear x y z
z

% they were deleted so reload them


load ('test')
z
.

EDHEC 2015: MATLAB Part 1 41


File Structures

Another example
save ('test', 'x','y') % overwrites
clear x y z

% they were deleted so reload them


load ('test')
x
z % error - it has been deleted
.
I do not require you to use .mat files, though you may like them. I will assume that
your data, both inputs and outputs, are stored in other formats such as EXCEL (in
other classes you may just be given a .MAT file).

EDHEC 2015: MATLAB Part 1 42


File Structures

2.6 Link to Microsoft EXCEL

The main data container we will use is Microsoft EXCEL. Spreadsheets are the most
commonly used tool for putting data together, sharing data and presenting results.
MATLAB links seamlessly to EXCEL, via the functions xlsread and xlswrite.
Inputting data is done with xlsread ('filename','sheetname'), which takes two
arguments. For example, create and save a spreadsheet called “test1.xlsx” in your
“Current Folder” (different paths can be used by adding them to the filename). Put
the value “1” in the top left cell in the worksheet “sheet1”, then run the following
code in MATLAB.
x=xlsread ('test1.xlsx','sheet1')
.
Writing data to spreadsheets is just as easy. First the spreadsheet must be closed.
y=1:10 ; xlswrite ('test1.xlsx',y,'sheet2')
.
Notice that the default is append, so you will only overwrite spreadsheet data where
the MATLAB matrix goes.

EDHEC 2015: MATLAB Part 1 43


File Structures

You can also control where exactly on the worksheet the data goes and create new
sheets automatically if they do not exist. For example
z=[11;12]
xlswrite ('test1.xlsx',z,'newsheet','B1:B2')
.
One error is that Inf, MATLAB speak for infinity, is translated in EXCEL as 65535.
And dates can be tricky. See the MATLAB help. We will deal with these issues as
they arise. The main fixes are to convert Inf to NaN (which EXCEL takes to be an
empty cell) and to format dates as strings before sending the EXCEL.
Note that MATLAB will even create a new spreadsheet if one with the name specified
doesn’t exist.
out=1:10
xlswrite ('testNEW.xlsx',out,'SOME_output')
.

EDHEC 2015: MATLAB Part 1 44


File Structures

2.7 Link to Plain Input/Output Files

You can also print straight to a plain file. This can be done with the low level function
fprintf. However, we will utilise a function from the MATLAB Statistics Toolbox
called tblwrite. This function is built on fprintf and allows you to specify row
names and column names. For example
data=[100,100,100; 110,115,88];
colnames={'stock a','stock b','my_stock'};
rownames={'period 1','period 2'};
tblwrite(data, colnames , rownames , 'output1.txt')
% same table but comma separated
tblwrite(data, colnames , rownames , 'output1_comma.csv',',')
.
If you do not have names for the columns and rows then either make some defaults
(of the correct length!) or type tblwrite(data) which will open a window to allow
you save a file manually.
There is also a function tblread that can be used to input formatted files. The
syntax is analogous to the write function.

EDHEC 2015: MATLAB Part 1 45


File Structures

2.8 Chart Files - MATLAB Format

The other main outputs from MATLAB that we will use in finance are charts. These
can be saved in a variety of formats. Start with simple scatter plot.
x=1:10; , y=1:10;
scatter(x,y)
.
This could be saved by first defining a figure object, printing the scatter plot and
then using saveas. For example
c1=figure; % opens a new figure object
scatter(x,y) % makes chart
saveas(c1,'chart1','fig') % MATLAB format
.
This code saved a .fig file in the Current Folder. It can be re-opened in MATLAB
(open('chart1.fig')). Note that you can use close to close the plot window.
There are many enhancements and formatting options for charts. We will examine
some of these later on.

EDHEC 2015: MATLAB Part 1 46


File Structures

2.9 Chart Files - Generic Format

A better way to store charts is to save them in a generic format (jpeg, png etc),
which can then be opened in WORD, EXCEL or whatever. For example
x=1:10; , y=1:10;
c1=figure; scatter(x,y);
saveas(c1,'chart1','png') % a generic format
.

EDHEC 2015: MATLAB Part 1 47


File Structures

2.10 Toolboxes

MATLAB “toolboxes” are essentially extra code, usually functions, that can be added
to any MATLAB installation. Once the file paths of a toolbox are added, toolbox
functions can be run and viewed like the built-in functions that your base MATLAB
installation comes with.
path % includes the paths of your the toolboxes installed on your system
.
Toolboxes are either purchased separately from the main MATLAB licence or, some-
times, shared freely.

EDHEC 2015: MATLAB Part 1 48


Matrices

3 Matrices

EDHEC 2015: MATLAB Part 1 49


Matrices

3.1 Goal

In this section you will learn how to create and handle matrices in MATLAB.

EDHEC 2015: MATLAB Part 1 50


Matrices

3.2 Creating Matrices

A matrix is a particular species of variable that can hold a lot of data. We will only
work with matrices of two dimensions (say, T rows and K columns). Call them what
you will (n, p, m, r, T, K or whatever), reference to the dimensions is by convention
row first and column second e.g. a 2 by 3 matrix means one with two rows and
three columns.
A “vector” is just a matrix where either T or K is one.
The simplest way to create a numeric vector is to type it into MATLAB with square
brackets, separating columns with a comma (or empty space) and rows with a
semicolon.
x=[ 1,2,3 ]
y=[ 3 4 5 ]
z=[1,2,3;4,5,6;7,8,9]
.

EDHEC 2015: MATLAB Part 1 51


Matrices

3.3 Matrix Size

The dimensions of a matrix are found with the command size, where you can
specify whether you want the number rows or columns (if neither is specified the
both are returned). For example
x=[ 1,2,3 ]
size(x), size(x,1), size(x,2)
.
Rows can be added by separating numbers with semicolon. For example
x=[1,2,3;1,2,3] , y=[3,4,5]
.
Matrices with matching dimensions can be easily combined. For example
z=[x;y] , size (z)
.
But notice the following is an error
z=[x,y] % error - dims not compatible
.

EDHEC 2015: MATLAB Part 1 52


Matrices

3.4 Re-shaping a Matrix

A trick that is sometimes useful is to “reshape” a matrix into another. The func-
tion reshape is able to mould a matrix into a different form if the dimensions are
compatible. For example
x=[1;2;3;4;5;6;7;8;9;10;11;12;13;14;15] % a 15 by 1 matrix
y=reshape(x,5,3) % a 5 by 3 matrix with the same numbers
z=reshape(y,3,5) % a 3 by 5 matrix with the same numbers
reshape(x,3,5) % same as z
reshape(x,4,4) % error - not possible
reshape(x,2,2) % error - not consistent
.
The data for reshaping is taken column-by-column, so be careful that a reshaped
matrix has ordered the data in the way you want.

EDHEC 2015: MATLAB Part 1 53


Matrices

3.5 Referencing the data that you want

Referencing the data in matrices looks complicated but is in fact simple. You use
round brackets after the matrix name, inserting the parts of the matrix that you want
to reference within the brackets. You need to specify which part of each dimension
that you want (except for a vector, which needs just one reference, but can take
both as well). For example take the following matrix
x=[1,2,3;4,5,6;7,8,9]
.
To reference the number in the second row and third column you type
x(2,3)
.
To reference all the numbers in a column or row use a colon. For example
x(2,:) % all data in row 1
x(:,1) % all data in column 1
.

EDHEC 2015: MATLAB Part 1 54


Matrices

To reference a subset of rows or columns you simply use a vector with index num-
bers for the parts that you want. For example
x([1 2],[2 3]) % rows 1 and 2, cols 2 and 3
.
Notice that you can use vector variables to do the referencing for you
rowstoget=[1,2];
colstoget=[2,3];
x(rowstoget,colstoget) % rows 1 and 2, cols 2 and 3
.
Finally, there are special ways to reference the end of a dimension. For example
x=[1,2,3;4,5,6;7,8,9]
x( 1:end , : )
x( 1:end , 1:end)
.
rowstoget=1:size(x,1);colstoget=1:size(x,2)
x(rowstoget ,colstoget)
.

EDHEC 2015: MATLAB Part 1 55


Matrices

3.6 Logical Referencing

You can also get the data that you want by using logical referencing, rather than
pointing to elements with index values. This very useful method requires logical
variables, either true or false, to indicate which elements to return. Details about
logical variables and how to use them for referencing is covered in sections (7.5)
and (7.6).

EDHEC 2015: MATLAB Part 1 56


Matrices

3.7 Data Generation Tricks - Vectors

There are a variety of tricks to create ready-made matrices and vectors. Useful
vector techniques include using two numbers split be “:”, splitting three numbers
by two colons and the function linspace.
nstart=1;nend=10; nstart:nend
1:10
nstart=1;nend=10;nstep=1;linspace(nstart,nend,nstep)
linspace(1,10,10)
1:1:10
.
These techniques are of most use when referencing a subset of data from a dimen-
sion of a matrix e.g. quickly referencing the first ten rows of a matrix x is done with
x(1:10,:).
Use linspace carefully.
linspace(1,10,9)
.

EDHEC 2015: MATLAB Part 1 57


Matrices

3.8 Data Generation Tricks - Matrices

Useful matrix generation techniques include using ones and the function zeros.
nrows=5;ncols=10;
ones(nrows,ncols)
zeros(nrows,ncols)
ones(10,1),zeros(1,10)
.
We will later use the zeros matrix to pre-allocate matrices that will subsequently be
filled-up with calculation results.
Another way to generate data is with repmat. This makes multiple copies of an
existing matrix. For example
x=1:10; % 1 by 10 matrix
repmat(x,1,5) % 1 by 50 matrix
repmat(x,5,1) % 5 by 10 matrix
repmat(x,5,5) % 5 by 50 matrix
.

EDHEC 2015: MATLAB Part 1 58


Matrices

3.9 Cell Arrays

Matrices in MATLAB must contain data of the same type i.e. numeric, strings. We
can use cell arrays, generated with curly brackets (“{ }”),
x={'string 1';'string 2'} % cell array of strings
y=[1.01;2.29;3.1009] % matrix of numbers
z={x,y} % cell array combination
.
Note that cell arrays can contain cell arrays as elements (i.e. there can multiple
levels of cell arrays within one structure).

EDHEC 2015: MATLAB Part 1 59


Matrices

3.10 Referencing Cell Array Data

Referencing the data that you want within cell arrays is done in an analogous way to
matrices. First, you use curly brackets to reference the element of the cell array that
you want. Then you use curly or square brackets to reference the data within that,
depending on whether it is string or numeric data (and how you want the output).
You can think of cell arrays as being analogous to structure variables, only that the
different parts of the array are referenced by numbers rather than names.
w={'string1','string2';'string3','string4'};
x={'first row';'second row';'third row'};
y=[1,2,3;4,5,6];
z={w,x,y}; % a cell array containing 2 cell arrays and 1 numerical matrix
z{1}
z{2:3}
z{1}{2,2} , z{1}(2,2) % which format do you want? (prob. the 2nd)
z{3}(2,:)
z{3}{2,:} % error (its a matrix ... )
.

EDHEC 2015: MATLAB Part 1 60


Matrices

3.11 A “Matrix” of Cell Arrays

A useful trick is to combine numeric data with strings by creating a matrix of cell
array data. First convert each variable into a cell array type. Then combine them
with square brackets to form a matrix (which works because the data is all of the
same “type”). Strictly speaking, the resulting matrix is a still a special type of cell
array.
Use num2cell to automatically convert numeric data to cell array data.
x={'col1 name','col2 name'} % cell array column names
y=[1.01,123;2.29,555;3.1009,323] % matrix of numbers
z=[x;num2cell(y)] % "matrix" of cell arrays
.
We will use this trick to combine output data with bits and pieces like column labels
and row name; especially when sending outputs and data analysis results to EXCEL
files.

EDHEC 2015: MATLAB Part 1 61


Matrices

3.12 Applying Functions to Each Element of a Matrix

It is possible to apply any function directly to each element of a matrix. This is


achieved with the help of a special MATLAB function arrayfun. This function’s
first argument is the function that you wish to apply, with an @ prefix. The second
argument is the matrix on which to operate.
However, it is often quicker and more straightforward to use the flexibility of the
underlying functions themselves – and many functions can be applied directly on
an element-by-element basis. For example
x=[1,2;3,NaN];
isnan(x) % identifies all elements that are 'NaN'
arrayfun(@isnan,x) % equvalent but slower
.
Customised functions that you write yourself can be applied in the same fashion
(using the @ prefix). Though, some other method of running your function, such as
using a for loop over each element, may be faster in any given case.

EDHEC 2015: MATLAB Part 1 62


Matrices

3.13 Applying Functions to Each Element of a Cell Array

It is also possible to apply any function directly to each element in a cell array using
cellfun. As for arrayfun, the first argument is the function that you wish to apply,
with an @ prefix, and the second argument is the cell array on which to operate.
This method is more useful for cell arrays than basic matrices. In particular, because
cell arrays can contain so many different types of data within one structure.
x=[1,2;3,4] ; y={'row name1','row name2'};
z={y,x}
isnumeric(z) % checks if overall structure is numeric
cellfun(@isnumeric,z) % checks each part of z
.

EDHEC 2015: MATLAB Part 1 63


Control Structures

4 Control Structures

EDHEC 2015: MATLAB Part 1 64


Control Structures

4.1 Goal

This section explains how to control the code execution of MATLAB scripts. The
goal is to be able to do things like repeat calculations until some conditions are met,
or to skip certain lines if a particular condition is not met.
It is convention to indent your code that is written within control structures (this does
not affect the MATLAB execution, but it is much easier to read and work on).

EDHEC 2015: MATLAB Part 1 65


Control Structures

4.2 FOR Loops

Loops repeatedly execute the same block of code. First, surround the code to be
repeated by for and end. Secondly, create a condition that stops the loop (lest
it go on forever). The condition is in the form of index counter that increments
automatically after each loop. For example
for i=1:10
[i , i/10] % or whatever code ...
end
.
x=randn(10,1)*100; % 10 by 1 matrix of random numbers
y=zeros(size(x,1),size(x,2)); % preallocated matrix of same size
for i=1:size(x,1)
y(i,1)=round(x(i,1));
disp([i,x(i,1),y(i,1)]) % disp() is neater
end
.

EDHEC 2015: MATLAB Part 1 66


Control Structures

4.3 WHILE Loops

Another type of loop is set by the command while. In this case the code inside the
loop will execute until the condition specified is met. When this goes wrong you will
get an infinite loop (!) - which you break out of by typing ctrl-c on your key board.
For example
x=randn(10,1);
counter=1; % initialise counter
while counter<=size(x,1)
y=round(x(counter)*100)/100;
disp([x(counter,1),y])
counter=counter+1;
end
.
We will focus on for loops in this class. Even then, we will use them with extreme
care: most of the things we want to do in MATLAB can be done directly on matrices,
rather than looping through the elements of a matrix.

EDHEC 2015: MATLAB Part 1 67


Control Structures

4.4 IF Conditionals

The most useful form of conditional in MATLAB is if. This allows you check a
condition and then choose what happens - for example make a calculation or skip
something. First, you open the if by checking some condition. Secondly, if the
condition is met then the subsequent code is run. If the condition is not met, then
the code between if and the end of the condition, denoted by end, will be skipped.
The if condition can be expanded neatly to encompass other conditions (ifelse)
and a default for when all other conditions are not true. Here is a simple example
clear x y biggest ; x=randn(10,1);y=randn(10,1);
if sum(abs(x))>sum(abs(y))
biggest=x; disp('x is biggest')
end
if sum(abs(x))<sum(abs(y))
biggest=y; disp('y is biggest')
end
biggest
.

EDHEC 2015: MATLAB Part 1 68


Control Structures

4.5 ELSEIF Conditionals

The code above can be better and briefer. First, we must account for the missing
case that sum(abs(x))==sum(abs(y)). Secondly, we can be more brief by using
one overall if condition, nesting other sub-conditions defined by elseif in it and
using a catch-all else at the end. For example,
clear x y biggest; x=randn(10,1);y=randn(10,1);
% x=y % try this to see catch-all working ...
if sum(abs(x))>sum(abs(y))
biggest=x; disp('x is biggest')
elseif sum(abs(x))<sum(abs(y))
biggest=y; disp('y is biggest')
else
biggest=NaN;disp('neither x nor y is biggest')
end
biggest
.
Note that you can use multiple ifelse commands within a single if condition.

EDHEC 2015: MATLAB Part 1 69


Control Structures

4.6 Nesting Loops and Conditionals

Loops and other conditionals can be usefully combined and nested. For example
nrows = 10; ncols = 10; data = ones(nrows, ncols);
for i = 1:nrows
for ii = 1:ncols
if i == ii
data(i,ii) = 2;
elseif abs(i - ii) == 1
data(i,ii) = -1;
else
data(i,ii) = 0;
end
end
end
data
.
The trick is to keep things as simple as possible. Too much nesting is unreadable
and prone to error.

EDHEC 2015: MATLAB Part 1 70


Control Structures

4.7 Vectorisation vs. Loops

MATLAB is slow with loops relative to “lower-level” languages such as C.


The term “vectorisation” refers to writing your code so that matrices are created, al-
tered, accessed and otherwise handled by directly referencing their elements. Typ-
ically MATLAB runs faster when code is vectorised rather than reliant on loops.
There are three issues here. First, vectorisation is not always faster than loops
– you can always experiment to check. Second, it may not be feasible to write
everything in vectorised form. Third, loops can sometimes be more “readable” or
understandable.
A few rules of thumb are:

• Try to vectorise from the start when managing large matrices.


• Using loops for formatting outputs and results is usually fine.
• If a loop runs unreasonably slow then try to vectorise the procedure in order
to speed-up performance.

EDHEC 2015: MATLAB Part 1 71


Control Structures

4.8 Other

Other commands exist to help control your code. These include switch with case
(replaces nested if clauses), try and catch (ensure a script keeps going when
trying to execute something that may cause an error), break (exit a loop), continue
(go back to start of loop) and return (stop everything).

EDHEC 2015: MATLAB Part 1 72


“Random” Numbers

5 “Random” Numbers

EDHEC 2015: MATLAB Part 1 73


“Random” Numbers

5.1 Goal

This section introduces how to generate and manage pseudo random numbers in
MATLAB. In general, I will refer to this process as “simulation”.
Note that these numbers are not really random in a physical sense – MATLAB gener-
ates random numbers based on highly unpredictable (by us) sequences from deter-
ministic formulas. But we will assume that MATLABs random numbers are “random
enough” for our purposes.

EDHEC 2015: MATLAB Part 1 74


“Random” Numbers

5.2 Generating Random Numbers

In general, generating random numbers from a particular distribution function (e.g.


the Normal distribution) is simple. The simplest method is produce a Uniform(0,1)
random number (a real number between 0 and 1) and work backwards from the
desired distribution’s cumulative density function.
We are not going to go into these details. For our purposes, MATLABs built-in
routines will produce the random numbers that we need.
In finance the ubiquitous, and often unfairly maligned, probability distribution is the
Normal distribution. There are two parameters in the Normal: mean and variance.
Note that standard deviation is the square root of variance. The way we will generate
Normal data is with the randn command, which generates N(0,1) matrices with as
many rows and columns as specified.
x=randn(10,1) % 10 rows and 1 col of N(0,1) data
.
We can adjust the mean and standard deviation of these numbers by simple addition
and multiplication of the N(0,1) numbers. For example

EDHEC 2015: MATLAB Part 1 75


“Random” Numbers

x=randn(10000,1);
y=.1+x*.15;
mean([x,y],1) % mean of columns
sqrt(var([x,y],[],1)) % sd (see "doc var" for details)
.

EDHEC 2015: MATLAB Part 1 76


“Random” Numbers

5.3 Other Useful Random Numbers

Two other useful automatic random number generating functions in MATLAB are
rand and randi. These produce matrices of random draws from the Uniform dis-
tribution. The first function, rand, draws from a U(0,1) and the other draws random
integer values between 1 and an integer input. For example
rand(10,5) % 5 columns of 10 random numbers between 0 and 1
randi(76,10,5) % 5 columns of 10 random numbers betwen 1 and 76
randi(11,5,3)+999 % 3 columns of 5 random numbers betwen 1000 and 1010
.

EDHEC 2015: MATLAB Part 1 77


“Random” Numbers

5.4 Setting the “Seed”

It is useful to be able to reproduce the same random numbers whenever you want.
This is particularly important when you want to compare the results of different cal-
culations on the same data (so, for example, you never need to save your simulated
data in a .dat file because you can just create everything again using the original
code).
MATLAB uses the function rng to set a “seed” for all its random number generations.
If you set the seed to a particular number and then generate a given set of random
numbers, the results will be the same.
x=randn(10,1); y=randn(10,1); [x,y]
myseed=101
rng(myseed) ; x=randn(10,1);
rng(myseed) ; y=randn(10,1); [x,y]
.
MATLAB generates its own seed if you do not set it. MATLAB increments all seeds
after each random generation task. But you can reset the seed to whatever you
want at any time.

EDHEC 2015: MATLAB Part 1 78


Matrix Algebra

6 Matrix Algebra

EDHEC 2015: MATLAB Part 1 79


Matrix Algebra

6.1 Goal

In this section you will learn how to do the most useful mathematical operations on
matrices. This includes both matrix algebra, for example multiplying two matrices,
and working on the data within a matrix on an element-by-element basis.

EDHEC 2015: MATLAB Part 1 80


Matrix Algebra

6.2 Element-by-Element Operations

Element-by-element
[ ] operations operate on the data within
[ 2 one
] matrix.
[ For
] example
1 2 1 22 1 4
Let x = . The element-by-element square of x is 2 2 = .
3 4 3 4 9 16
In MATLAB this is:
x=[1,2;3,4]
x.^2
.
Notice the “.” used before the usual symbol “ˆ” which designates “to-the-power-
of”. Doing element-by-element operations for multiply and divide is similar: you just
need to add a “.” to the usual symbols. Otherwise you will be doing real matrix
algebra (see next section).
Adding and subtracting in real matrix algebra is an element-by-element operation,
so no dot is added to + or -.
Note that if you simply want to multiply or divide by a scalar (i.e. a number) you do
not have to use the ., but it still works.

EDHEC 2015: MATLAB Part 1 81


Matrix Algebra

x=[1,2;3,4]
x*2,x.*2
x+2 % element-by-element
.
If you want to multiply, add, divide or subtract two matrices then they must be the
same dimension. And you must use the . with the usual operators with * and /.
For example
x=[1,2;3,4];y=x
x.*y
x./y
x+y % no dot
x-y % no dot
.

EDHEC 2015: MATLAB Part 1 82


Matrix Algebra

6.3 Element-by-Element Functions

Many built-in MATLAB functions apply by default on a element-by-element basis.


Examples include log and exp. This is very useful. For example
x=[.1,.15;.05,.075]
log(1+x)
exp(log(1+x))-1
.
Always check how a function works before using it.

EDHEC 2015: MATLAB Part 1 83


Matrix Algebra

6.4 Advanced Element-by-Element Operations

Sometimes you will want to do complicated element-by-element operations that


are not automatic. The slowest-but-surest way to do this is to loop through each
member of the matrix and do the operation one-by-one. This can be slow if the
matrix is large.
Several short-cut methods exist in MATLAB to speed this up. These include bsxfun
and arrayfun.
We will examine these functions later in the course, if we get time. They are not
essential.

EDHEC 2015: MATLAB Part 1 84


Matrix Algebra

6.5 Proper Matrix Algebra

The matrix algebra we will use in this course is straight-forward. We will multiply,
divide, add and subtract matrices. Division of matrices is tricky, but we will limit
ourselves to dividing by square matrices, which is straight forward.
Any complex formula that we use can be broken down into a series of steps, with
two matrices combining at each step.
The most important thing to know is that in each step the dimensions of the two
matrices must be compatible with the operation.
Assume x is a T (rows) by K (columns) matrix and y is some other matrix.

Operation MATLAB Code Dimension Requirement


add x+y x and y must have same no. rows & cols
subtract x-y x and y must have same no. rows & cols
multiply x*y y must have as many rows as x has cols
left divide x\y x and y must have same no. rows
right divide x/y x and y must have same no. cols

EDHEC 2015: MATLAB Part 1 85


Matrix Algebra

The “division” of matrices in MATLAB is more complex than regular algebra. In


addition to the operators shown in the table above there is also inv which computes
the inverse of a matrix. For a square matrix x (a square matrix has the same number
of rows as columns)

inv(x) ∗ y ≈ x\y

In practice, we will use the more efficient “left divide” method, even when working
with square matrices.
A further rule is the exponent (to-the-power-of) operator “ˆ” can only apply to square
matrices. This rule is just an implication of the multiply rule in the table above.

EDHEC 2015: MATLAB Part 1 86


Matrix Algebra

6.6 What is going on?

Matrix multiplication is simple. The operation matches each row of the left-hand-
side matrix with each column of the right-hand-side matrix. Each element of the
result matrix is the sum of the product of corresponding left-hand-side row elements
times the right-hand-side column elements. This is best explained by example:
[ ] [ ]
1 2 1 2 3
let x = and y = .
3 4 4 5 6
[ ]
(1 ∗ 1 + 2 ∗ 4) (1 ∗ 2 + 2 ∗ 5) (1 ∗ 3 + 2 ∗ 6)
Then x ∗ y =
(3 ∗ 1 + 4 ∗ 4) (3 ∗ 2 + 4 ∗ 5) (3 ∗ 3 + 4 ∗ 6)

x=[1,2;3,4]
y=[1,2,3;4,5,6]
x*y
.
In general, multiplying a N by K matrix with a K by M matrix will result in a N by
M matrix; where each element of the resulting matrix is the sum of the products of
the corresponding elements of the first two matrices.

EDHEC 2015: MATLAB Part 1 87


Matrix Algebra

Matrix addition and subtraction just adds and subtracts corresponding elements.
Understanding matrix “division” is more tricky; the details of this are for another class
(econometrics, for instance), but we can still do it with MATLAB.

EDHEC 2015: MATLAB Part 1 88


Matrix Algebra

6.7 Transpose

A trick we will often use is the matrix transpose, which switches the dimensions of a
matrix. This is useful to get the dimensions to match for various operations between
matrices.
[ ] [ ]
1 2 1 3
For example let x = . The transpose of x is x′ = .
3 4 2 4
Note that sometimes this is written with “T” like xT .
In MATLAB the “'” symbol transposes a matrix. For example
x=[1,2,3;4,5,6]
x'
size(x)
size(x')
.

EDHEC 2015: MATLAB Part 1 89


Matrix Algebra

6.8 More Examples

More examples of valid and invalid matrix operations include the following.
x=[1,2,3;4,5,6] % 2 by 3
y=repmat(1,size(x,2),4) % 3 by 4
z=randn(3,3) % square matrix

y*x % error

x*y
y'*x'

inv(z)*z % identity matrix (like dividing by itself)


z\z % identity matrix
z\y
.

EDHEC 2015: MATLAB Part 1 90


Relations and Logic

7 Relations and Logic

EDHEC 2015: MATLAB Part 1 91


Relations and Logic

7.1 Goal

In this section you will learn how to produce and handle first order logical operations
in MATLAB.
In practice, this simply means generating true and false values from matrices.
And then using these values in subsequent calculations and to select sub-sets of
data via referencing.

EDHEC 2015: MATLAB Part 1 92


Relations and Logic

7.2 Relations

It is easy and useful to compare numerical values and matrices in MATLAB. A sum-
mary of comparative operators we will use is as follows.

MATLAB Code Operation


== Equal
∼= Not equal
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal

These operators result in true or false “logical” values.


Note that for strings in cell arrays use strcmp to test for equality.

EDHEC 2015: MATLAB Part 1 93


Relations and Logic

7.3 Logic

It is also easy and useful to compare logical values or conditions in MATLAB. A


summary of comparative operators we will use is as follows.

MATLAB Code Operation


&& logical “AND” (use to compare scalars)
|| “OR” (use to compare scalars)
& element-wise “AND” (use to compare matrices)
| element-wise “OR” (use to compare matrices)
∼ “NOT”

We will normally only use the last three in the table above - they work for scalars
and matrices.

EDHEC 2015: MATLAB Part 1 94


Relations and Logic

7.4 Matrix Checks

There are variety of useful checks that can be carried out on MATLAB matrices. For
example

MATLAB Code Operation


any True if any element of vector is nonzero
all True if all elements of vector are nonzero
isempty True if matrix is “[ ]”
isnan True if element is “NaN”
isequal True if one matrix is equal to another
isnumeric True if matrix is numeric (cf. char)
islogical True if the data is logical (true or false)

The any and all functions can be used on either rows or columns of matrices by
specifying the dimension e.g. all(x,1) checks for nonzeros by rows.
See doc is* for more details and checks.

EDHEC 2015: MATLAB Part 1 95


Relations and Logic

7.5 True or False

The default data storage of the logical outcomes “true” and “false” in MATLAB are
what looks like “1” and “0” respectively. For example
2.5==2.5
5<0
[ repmat(true,5,1) , repmat(false,5,1)]
.
These are not numeric values. But you can use them with MATLAB functions such
as sum and normal operations like addition and so on (with MATLAB doing an au-
tomatic “transform”). Note that logical will convert 0 and 1 to logical values.
x=[true;false;true]; y=[1;0;1]
[sum(x),sum(y)] , [x*100 , y*100]
[islogical(x) , islogical(y);isnumeric(x),isnumeric(y)]
y(x) % logical reference element-by-element
x(y) % error (no zero position)
x(logical(y)) % convert zeros and ones to logicals
.

EDHEC 2015: MATLAB Part 1 96


Relations and Logic

7.6 Logical Referencing

Referencing data within matrices can be done by supplying logical values to identify
the elements that you want.
x=[true;false;true]; y=[1;3];
data=[1;2;3] ; data2=[1,2,3;4,5,6;7,8,9]

data(x)
data(y) % no need to specify pair for a vector
data(y,1) % but you can ...

data2(x,3)
data2(y,3)

data2(:,x)
data2(:,y)
data2(repmat(x,1,3)') % data returned as a vector
.

EDHEC 2015: MATLAB Part 1 97


Relations and Logic

7.7 Example: Missing Values

So-called “missing values” are common in financial time series, for example when
there are some securities that don’t have histories as long as others.
As already mentioned, MATLAB stores missing values as “NaN”. This allows you to
create and use matrices with some missing values. But you need to take care that
your calculations do not try to use the NaN.
Many functions discard missing values by default. Other functions need to told
to ignore them or have a different matching function that can be run (usually the
function name is the same but with a suffix of “nan”). For example see the Help
documentation for calculating means in the presence of missing values:
doc nanmean
.
A different and more sure-fire approach to missing values is to remove them before
doing calculations. This is straightforward: you first identify which elements of a
matrix are NaN then you work with these elements removed.

EDHEC 2015: MATLAB Part 1 98


Relations and Logic

% a vector with some NaNs at start and end


x=[ repmat(NaN,1,9) , 1:10, NaN]'

% an index of logicals to identify missing values


xmissing=isnan(x)
x(~xmissing)

% compare the 3 outputs


mean(x),nanmean(x),mean(x(~xmissing))
.

EDHEC 2015: MATLAB Part 1 99


Relations and Logic

7.8 More Examples

More examples of comparisons and logical checks of both scalars and matrices
include
x=randn(10,1);y=randn(10,1);
[ x,y, [x>0]&[y>0] , [x>0]|[y>0] ]

x=1+2 ; y=randn(1,1);
x>0&&y>0
x>0&y>0
.

EDHEC 2015: MATLAB Part 1 100


Functions

8 Functions

EDHEC 2015: MATLAB Part 1 101


Functions

8.1 Goal

In this section you will learn how to create and use MATLAB functions.

EDHEC 2015: MATLAB Part 1 102


Functions

8.2 MATLAB functions

Lots of useful functions already exist in MATLAB. The output of functions can be
directly assigned to variables. For example
x=rand(1,100) % generate 100 random numbers
y=mean(x) % calculate a mean
.
Many functions can be told to operate on either the rows or columns of a matrix.
Not specifying which will result in a default choice, which is not always consistent
across functions (so check the Help files). For example
x= randn(100,5) % 5 columns of 100 random Normal numbers
doc mean
mean(x,1) % calculate mean of cols
mean(x,2) % calculate mean of rows
.

EDHEC 2015: MATLAB Part 1 103


Functions

8.3 Functions are Files

All MATLAB functions are just written in files, with one function per file. For example
see
which mean
open mean
.
All our own functions will be along the similar lines – with each function defined in
its own .m file.

EDHEC 2015: MATLAB Part 1 104


Functions

8.4 A Test Function

Open a new script file and save the file as “FNtest1’. Then paste the following code
into the file and save again.
function out = FNtest1()
out = 'my premier output';
end
.
Back in the Command Window type
x=FNtest1
.
The function output (designated by the out variable) is assigned to x.

EDHEC 2015: MATLAB Part 1 105


Functions

8.5 A Test Function with Inputs

Now we will add an input variable called in (you can call the input and out variables
anything you like).
function out = FNtest1(in)
out = 10*in;
end
.
Run this as
FNtest1(9.9)

y=1:10;
FNtest1(y)

z=[1 2 ; 3 4];
FNtest1(z)
.

EDHEC 2015: MATLAB Part 1 106


Functions

8.6 Functions with Multiple Inputs and Outputs

Open a new script file and save the file as “FNtest2’. Then paste the following code
into the file and save again.
function [out1,out2] = FNtest2(in1,in2)
out1.premier = 10*in1; % structure variable
out1.deuxieme = 100*in1;
out2 = NaN;
end
.
This function can now be called from a script or directly in the Command Window.

FNtest2(1,2)
FNtest2(1) % no error because 2nd input not used
x=FNtest2(1,2);x.deuxieme
[x y]=FNtest2(1,2); x , y
.

EDHEC 2015: MATLAB Part 1 107


Functions

8.7 Order Matters for Inputs and Outputs

When you read other people’s MATLAB code and the MATLAB Help files you will
notice that there are a variety of short-cuts and short-hand notation. These include
not specifying optional inputs and only specifying the outputs that you want. The
different short-cuts can be confusing.
The main thing to remember is that both input and output variables for MATLAB
functions must be entered in the order specified by the function code. This means,
for example, that if you want to specify a third input, in3 say, then you must specify
something for first two input variables (even if you specify that they are nothing by
using “[ ]”).
The same goes for outputs (where you can use “∼” to signify that you do not want
an output).

EDHEC 2015: MATLAB Part 1 108


Functions

8.8 Order Matters Example

Open a new script file and save it as “FNtest3”. Then paste the following code into
the file and save again.
function [out1 , out2 , out3] = FNtest3(in1,in2,in3)
out1.premier = 10*in1;
out1.deuxieme = 100*in1;
out2 = NaN;
out3 = in3;
end
.
[x , ~ , z]=FNtest3(100,[],20); z % ok
[x , y , z]=FNtest3(100,10); z % error
[~ , ~ , z]=FNtest3([],[],20); z % ok
.

EDHEC 2015: MATLAB Part 1 109


Functions

8.9 Function Rules-of-Thumb

Some good rules-of-thumb for your own code relating to functions are the following.

• Only use the input and output variables you will need when you build functions.
• If you define an output variable then make sure you assign it something.
• Use commas to separate variables when building and calling functions (not
essential but tidy).
• When you call a function with optional inputs then try using a “[ ]” place-holder
for the unneeded bits.
• When you call a function with unwanted outputs then try using a “∼” place-
holder for the unwanted bits.
• Keep things simple - so do not try to account for almost-redundant scenarios
that may need optional inputs or outputs.

EDHEC 2015: MATLAB Part 1 110


Functions

8.10 Optional Parameters to Functions

Note that you may come across nargin and nargout, which automatically count
the number of input and output parameters, respectively, to a MATLAB function.
By checking these counts, a function’s code can be adjusted when only some of
the parameters are passed. For example
function [out] = FNtest4(in1,in2)
if nargin < 2
in2='not used';
end
out.one=in1*100;
out.two=in2;
end
.

EDHEC 2015: MATLAB Part 1 111


Functions

8.11 Anonymous Functions

Occasionally we will use the following trick for running functions. The trick consists
of defining a so-called “anonymous function” within a MATLAB script, rather than
saving a separate function file. This type of function is only able to be run after its
section within the script in which it appears is run (c.f. functions defined in their own
files).
An anonymous function is assigned to a name, its inputs are denoted at the start
of the function within a @(), and then the function is defined. This style suits short
functions, for example
% define a function
afun=@(x,y)(x^2+y^2-x*y);

% call the function


afun(10,9)
.

EDHEC 2015: MATLAB Part 1 112


Functions

8.12 Anonymous Functions From Files

Functions from files can serve as a base for anonymous functions. For example
% save this function
function [out] = FNtest5(a,b)
out=(a^2+b^2-a*b);
end
.
afun2=@(x)FNtest5(10,x);
afun2(9)
.
You need to use variables carefully, for example
y=9;
afun3=@(z)FNtest5(z,y);
afun3(10)
.
Finally, note that regular MATLAB functions (saved in files) can define and use inter-
nal anonymous functions as well.

EDHEC 2015: MATLAB Part 1 113


Functions

8.13 Sub-Functions

It is possible to put more than function in an .m file. But only the first one will be
callable from outside of the particular .m file. This would enable the first function to
call sub-functions, perhaps making the code tidier and easier to understand.
We will not do this.

EDHEC 2015: MATLAB Part 1 114


Functions

8.14 More Complex Examples

We will do many more complex examples in the applications that follow ...

EDHEC 2015: MATLAB Part 1 115


Optimisation

9 Optimisation

EDHEC 2015: MATLAB Part 1 116


Optimisation

9.1 Goal

This section introduces how to optimise functions in MATLAB. More details will be
added when we look at applications.

EDHEC 2015: MATLAB Part 1 117


Optimisation

9.2 Optimising What?

We will assume that we wish to optimise some mathematical function. In this con-
text, the function will be some form of MATLAB equation with algebraic parameters.
Some of the parameters will not be fixed, in the sense that we assume they are free
to vary. MATLAB optimisation routines will seek to find the values for the free pa-
rameters at which the overall function has a maximal or minimal value.
Note that finding a maximum of a function value is the same as minimising the neg-
ative value of the same function. By default MATLAB minimises functions.
Optimisation is not always a precise science. For example there is no guarantee of
finding a “global” solution for complex non-linear functions. And sometimes no so-
lution is able to be found. In such cases, the set-up of the function being optimised
and/or the optimisation routine may require careful attention.
There may be constraints on the values that the free parameters can have (e.g. that
they must be greater than zero). These can be accounted for by particular MATLAB
routines.

EDHEC 2015: MATLAB Part 1 118


Optimisation

9.3 MATLAB Help

MATLAB has a variety of built-in optimisation routines (or “solvers”, if you like). There
are even more in the MATLAB “Optimisation Toolbox”. Choosing the right routine
for the job at hand can be tricky – they all work in different ways and some may give
misleading results when others would not.
The Help documentation of the Optimisation Toolbox is useful. Type doc in your
Command Window to open the help documentation and then search for “Opti-
mization Decision Table”. The Help section under this title gives a good description
of which routine to use for what job.

EDHEC 2015: MATLAB Part 1 119


Optimisation

9.4 Technical Tips


• Always be clear, before you write any code, which variables are to be optimised
and which are simple numerical inputs for which you have data.
• For complex functions with multiple inputs you should first make a separate
.m file with the code within it. Then you can make an anonymous function that
calls this function. In the call you should add all the data inputs that you have
and leave only the variable to be optimised as an input. Then you can use this
second function in the optimisation routine.
• In most problems you need to provide MATLAB with an initial guess of the
variables to be optimised.
• In cases where the optimisation routine produces an error you can: try to
increase the number iterations it runs; adjust the stopping “tolerance”; try dif-
ferent initial guess values. See the Help files for more information about this.

EDHEC 2015: MATLAB Part 1 120


Optimisation

9.5 Typical Output

MATLABs optimisation routines typically output several results.

• The optimal parameter values that have been found.


• The value of the overall objective function at these values.
• An “exitflag” indicating why the MATLAB routine stopped: 1 means a conver-
gence to an optimal value.
• Some more details about the routine used, number of iterations completed
etc.

EDHEC 2015: MATLAB Part 1 121


Optimisation

9.6 Routine Options

Each routine comes with various options to set. There are defaults, so you can try
running your code without changing anything. If there is a problem, MATLAB will
often give you a useful hint about how to change the options.
Options are set with a command called optimset. This can be assigned to a variable
and fed back into the particular optimisation routine.

• Common examples of options to adjust are the underlying algorithm used by


the routine (Algorithm), the maximum number of iterations to use (MaxIter)
and the convergence tolerance (TolFun).
• The Help file for each routine will give appropriate guidance in each case.

EDHEC 2015: MATLAB Part 1 122


Optimisation

9.7 Three Useful MATLAB Routines

We will restrict our attention to MATLAB optimisation routines called fminsearch,


fmincon and quadprog.
The first, fminsearch, will efficiently minimise non-linear functions that have no con-
straints (linear functions are also handled, but there may be more efficient methods).
The second, fmincon, is the most general and will minimise linear and non-linear
functions, with or without, constraints. The main cost of fmincon is usually speed.
And the many options with respect to constraints makes using the routine tricky.
The last, quadprog, works specifically for quadratic functions and handles straight-
forward constraints on these.

EDHEC 2015: MATLAB Part 1 123


Optimisation

9.8 Simple Optimisation Example

A simple example of a MATLAB equation to minimise is the following.


testfun1 = @(x) ( x.^2 );
plot(-4:.1:4 , testfun1(-4:.1:4)) ; grid on ; xlabel('x')

x0=[1] % initial guess

[x,fval,exitflag,output] = fminsearch(testfun1,x0)
[x,fval,exitflag,output] = fmincon(testfun1,x0,0,0)

% constraint: x must be <= -2


[x,fval,exitflag,output] = fmincon(testfun1,x0,[1],[-2])

hold on; scatter(-2,testfun1(-2),'*','MarkerEdgeColor','red');hold off


.
Note that if the function to be minimised is saved in a .m file it must be preceded by
a “@” in the optimiser code.

EDHEC 2015: MATLAB Part 1 124


Optimisation

9.9 More Complex Optimisation 1

A more complex example is maximising a “log likelihood” function. This has multiple
parameters and a complex form. Also, we want to input some sample data and only
optimise with respect to the parameters of the Normal distribution.
The code below sets up the problem and we solve the function on the next page.
% some sample data (where we know mu=0 and sigma=0)
xtest=randn(100,1); % random N(0,1)

% log likelihood of iid Normal data (want to maximise this)


testLL = @(x,mu,sigma) ( log( prod( 1/(sigma*sqrt(2*pi))* ...
exp(-(x-mu).^2/(2*sigma^2) ) )) )

% make another function to input data and only leave Normal parameters
testfun3=@(x)( testLL(xtest,x(1),x(2)))

% initial guesses (assume the sample is real and you do not know ... )
x0=[.5,.5];
.

EDHEC 2015: MATLAB Part 1 125


Optimisation

9.10 More Complex Optimisation 2

The code below tries to maximise the log likelihood function on the previous page.
We know the result x vector should be close to 0 and 1 because our simulated data
were N(0,1).
% NOTE: Requires MATLAB 2015 or later to work, except x3 and x4
% wrong way around (may diverge or result in NaN)
[x1,fval,exitflag,output] = fmincon(testfun3,x0,[0,0],[0])
[x2,fval,exitflag,output] = fmincon(testfun3,x0*-1,[0,0],[0]) % different answer

% right way - take a minus ... and then minimise (should be close to 0 and 1)
testfun4=@(x)( - testLL(xtest,x(1),x(2)))
[x3,fval,exitflag,output] = fmincon(testfun4,x0,[0,0],[0])
[x4,fval,exitflag,output] = fmincon(testfun4,x0*-1,[0,0],[0])

% constraints (guess what they are?)


[x5,fval,exitflag,output] = fmincon(testfun4,x0,[],[],[1,0],[0])
[x6,fval,exitflag,output] = fmincon(testfun4,x0*-1,[0,-1],[0])

[x1;x2;x3;x4;x5;x6]
.
EDHEC 2015: MATLAB Part 1 126
Optimisation

9.11 Older Versions of MATLAB

To run the sensible examples on the previous page for versions of MATLAB before
2015 you can try changing the default setting for the Algorithm to “interior-point”.

% For MATLAB 2013 ...


options = optimset('Algorithm', 'interior-point');
[x7,fval,exitflag,output] = fmincon(testfun4,x0,[0,-1],[0], ...
[],[],[],[],[],options)
.

EDHEC 2015: MATLAB Part 1 127


Optimisation

9.12 Quadratic Example

The syntax for the quadratic optimiser is different. In this case, the function to
minimised is always of the following form

1
min x′Hx + f ′x, (1)
x 2
subject to the conditions that Ax ≤ b, Aeq x = beq and l < x < u.
So the MATLAB code is based on inputting the different pieces of equation (1) and
the conditions that you want.

EDHEC 2015: MATLAB Part 1 128


Optimisation

9.13 Quadratic Example Code

% define inputs
H = [ 0.005, -0.010, 0.004; -0.010, 0.040, -0.002; 0.004, -0.002, 0.023] ;
n = 3 ; f = zeros(n , 1) ; Aeq = ones(1 , n) ; beq = 1 ;
l = zeros(n , 1) ;

% run optimization (may need options changing)


[ x , ~ , exitflag ] = quadprog(H,f,[],[],Aeq,beq,l)

% change options?
opts = optimset('Algorithm','interior-point-convex');
[ x , ~ , exitflag ] = quadprog(H,[],[],[],Aeq,beq,l,[],[],opts)
.

EDHEC 2015: MATLAB Part 1 129


Basic Charts

10 Basic Charts

EDHEC 2015: MATLAB Part 1 130


Basic Charts

10.1 Goal

This section is a brief introduction to charts in MATLAB.


Much more detail on MATLABs extensive plotting abilities are contained in the Help
files. For example open the documentation with doc and click through the folder
tree to
MATLAB–>Getting Started–>Graphics
and
MATLAB–>Functions–>Graphics
Note that an introduction to handling chart files was covered in section (2.8).

EDHEC 2015: MATLAB Part 1 131


Basic Charts

10.2 Basic Charts

There are many automatic chart types in MATLAB. These include plot, scatter
and hist. For example,
x=randn(100,1);y=randn(100,1);

plot(x,y)
scatter(x,y)
hist(x)
.
Notice that by default MATLAB uses the same figure object for each chart (i.e. each
chart overwrites the previous one). To make a new figure object for each chart use
the figure command each time you want to make a new chart.

EDHEC 2015: MATLAB Part 1 132


Basic Charts

10.3 Titles and Labels etc

The most typical things added to charts are done with title, xlabel and ylabel.
Many other options exist, however.
x=randn(100,1);y=randn(100,1);
scatter(x,y);
xlabel('the x values')
ylabel('the y values')
title('Some Fake Data')
.

EDHEC 2015: MATLAB Part 1 133


Basic Charts

10.4 Multiple Charts

New figures are created and focused on by issuing a figure command. Assigning
this command to different variables allows you to easily switch between charts and
make adjustments as required. For example
x=randn(100,1);
y=randn(100,1); % some random data
c1=figure; % new figure (automatically the focus)
scatter(x,y); % a scatter on focused figure
c2=figure; % new figure (is the focus now)
plot(x,y); % a line plot on c2

figure(c1); % change focus back to c1


title('This is Chart 1') % Title for c1
figure(c2); % change focus back to c2
title('This is Chart 2') % Title for c2
.

EDHEC 2015: MATLAB Part 1 134


Basic Charts

10.5 Saving and Deleting Charts

Figures can be deleted with close and saved with saveas. This is easy to do when
figures are assigned to variable names. For example
x=randn(100,1); y=randn(100,1);
c1=figure; scatter(x,y);
c2=figure; plot(x,y);
saveas(c2,'chart2','png')
saveas(c1,'chart1_MATFORMAT','fig')
close(c1),close(c2)
.
Note that saveas enables you to save charts in a variety of different formats (see doc
saveas). And that .fig files can be re-opened in MATLAB (using open), while other
formats like .png can be inserted into Microsoft WORD/EXCEL files or websites.

EDHEC 2015: MATLAB Part 1 135


Basic Charts

10.6 Multi-charts

A useful trick is to plot more than one chart on the same figure. This is done with
subplot, which creates a m by n matrix of plots within one figure object.
x=randn(100,1);y=randn(100,1);

% create a 2 by 1 matrix of charts. Do one at a time.


subplot(2,1,1), scatter(x,y); % 2 by 1, 1st chart
xlabel('the x values');
ylabel('the y values');
title('Some Fake Data');

subplot(2,1,2), hist(x); % 2 by 1, 2nd chart


title('Histogram of x')
.

EDHEC 2015: MATLAB Part 1 136


Basic Charts

10.7 Basic Chart Options

Basic chart options can be set within the chart function. This simply requires stating
the option and the value to which it can be set in the original plot function. Alterna-
tively, you can assign the plot to a variable and adjust the options later (directly in
MATLAB 2015 or use the set command for earlier versions).
x=randn(100,1);y=randn(100,1);

subplot(1,2,1);p1=scatter(x,y,'MarkerEdgeColor','red','Marker','+');
subplot(1,2,2);plot(x,y,'Color','blue');

% run this after checking the plots above


% MATLAB 2015
p1 % view options
p1.MarkerEdgeColor = 'yellow'; p1.Marker='>'; p1.LineWidth = 2;
% MATLAB 2013
set(p1,'MarkerEdgeColor','yellow') % ...
.
Check the Help file for each function to see which options can be set and how (e.g.
colours have different specifications).
EDHEC 2015: MATLAB Part 1 137
Basic Charts

10.8 Multiple Series

The hold function can allow you plot multiple times on the same figure. This would
typically be combined with different colours, symbols, line widths etc. You can also
add a legend (pass each plot handle first to ensure formats match).
xy1=randn(100,2); xy2=randn(100,2);
hold on
p1=scatter(xy1(:,1),xy1(:,2),'MarkerEdgeColor','red');
p2=scatter(xy2(:,1),xy2(:,2),'Marker','x','MarkerEdgeColor','blue');
legend([p1 p2],'xy1','xy2') % each plot passed to ensure format
hold off

figure
hold on
p3=scatter(xy1(:,1),xy1(:,2),'Marker','^','MarkerEdgeColor',[0,.5,1]);
p4=plot(-5:5,-5:5,'LineWidth',[4],'Color', [0.8,.4,0.54]);
hold off
.

EDHEC 2015: MATLAB Part 1 138


Scripts

11 Scripts

EDHEC 2015: MATLAB Part 1 139


Scripts

11.1 Goal

In this section you will learn how to create and run useful MATLAB scripts. Then,
finally, we can attack complex financial applications!

EDHEC 2015: MATLAB Part 1 140


Scripts

11.2 Basics

A basic script is set of MATLAB commands saved as a .m file. A script is run by


pressing the green arrow key on the Editor or by pressing F5 on the keyboard.
The script can include calls to functions and run other scripts. For example save
x=1; in a file called 'script1'. The create and save another script called 'script2'.
In this second script type the follow command.
clear;
run('script1');
x
.
On running 'script2' you will see that x has taken the value from the script 'script2'.
In this class we will only work with one script at a time, but any given script may be
required to call several functions.
Create a new file called script3. Then save and run the following code in it.

EDHEC 2015: MATLAB Part 1 141


Scripts

clc;clear; % clean everything


x=randn(100,1); % make some random numbers
mean(x) % call then mean function
sqrt(var(x)) % call the var and sqrt functions
.

EDHEC 2015: MATLAB Part 1 142


Scripts

11.3 Debugging

You will often make syntax mistakes. MATLAB will trap each error for you and try
to guide you to where the problem is. Then you have to fix it and re-run the code.
This is an iterative process and will take some getting used to.
The example below yields a more-or-less informative error when calling the function
from a script: there is hyper-link a link to the function code.
% save function in its file and close file
function [out] = FNmultiply(x,y)
out=x*y;
end
.
a=randn(10,2) ; b=rand(10,2);
FNmultiply(a,b) % run from a script
.
You can also set so-called “break points” at which the code execution will pause,
so that you can inspect results and variable assignments to-date. The Help section
on “Setting Breakpoints” has a good explanation of how this works. We will also do
some examples in class.
EDHEC 2015: MATLAB Part 1 143
Scripts

11.4 Variable Scope

Loosely speaking the “scope” of a variable means where it lives, which dictates how
or if it can be accessed by other code.
The scope of variables created inside functions is limited to that function.
Variables from scripts can be used within scripts but must be sent explicitly to func-
tions.
It is possible to create “global” variables that can be used and altered by functions
without being passed explicitly. But we will not use these as they are messy and
almost always unnecessary.

EDHEC 2015: MATLAB Part 1 144


Scripts

11.5 Planning a Script

When you are doing proper work (like homework for this class) always write a plan
for your scripts. An ordered list of what your program needs to do will suffice.

• Make frequent use of code comments.


• Preallocate any output matrices i.e. matrices that will be filled with data within
a loop. Starting with NaNs or zeros is a good idea.
• Use vector indexing instead of loops when you can.
• Don’t use global variables unless necessary (we will not use them).

EDHEC 2015: MATLAB Part 1 145


Scripts

11.6 Miscellaneous Advice


• When writing complex scripts start with simple cases, then add layers of com-
plexity as you go.
• Don’t wait until you are finished to run (F5) your code - keep checking as you
go!
• Try to have your script print out results and variable assignments as you go
(they can be suppressed at the very last stage).
• Use a double comment (“%%”) to create script “sections” and then run just the
code from within a particular section.

EDHEC 2015: MATLAB Part 1 146


Basic Probability

12 Basic Probability

EDHEC 2015: MATLAB Part 1 147


Basic Probability

12.1 Goal

This section is an introduction to basic probability functions from the Statistics Tool-
box.
The details of probability are for other courses – but you should be able to con-
fidently use MATLAB as you learn about hypothesis testing, econometric models
and probability theory.

EDHEC 2015: MATLAB Part 1 148


Basic Probability

12.2 Probability Distributions

The main probability distributions you will use are the Normal, Student-T, Chi-squared
and F distributions. In MATLAB the following functions represent probability density
functions for the first three: normpdf, tpdf and chi2pdf.
In this course we will only use cumulative distributions: normcdf, tcdf and chi2cdf.
% Normal with mean 0 and sd 1.
x=-5:.1:5;
subplot(2,1,1);scatter(x, normpdf(x,0,1));title('pdf N(0,1)')
subplot(2,1,2);scatter(x, normcdf(x,0,1));title('cdf N(0,1)')

% Chi-sqr with 2 degrees of freedom---


y=0:.05:10; figure
subplot(2,1,1);scatter(y, chi2pdf(y,2));title('pdf Chi-sqr(2)')
subplot(2,1,2);scatter(y, chi2cdf(y,2));title('cdf Chi-sqr(2)')
.

EDHEC 2015: MATLAB Part 1 149


Extensions

13 Extensions
A variety of interesting and advanced topics were not covered above. These include
the following.

• Specialist topics such as symbolic mathematics and string manipulation.


• Advanced topi—cs such as object-orientated programming.
• Index referencing different pieces of a matrix in one go (sub2ind).
• Concatenating or collapsing matrices or cell arrays (e.g. vertcat).
• Advanced charting - specialised types, line style changes, 3 dimensions etc.
• Advanced statistical distribution theory and methods of the Statistics Toolbox.
• Memory management and benchmarking code efficiency (e.g. tic & toc).
• Linking your own C and FORTRAN scripts with MATLAB.

EDHEC 2015: MATLAB Part 1 150


Index
∼, 94, 108, 110 all, 95
∼=, 93 ans, 27
,, 32 any, 95
..., 32 arrayfun, 62, 63, 84
.fig, 46
.m, 40 break, 72
.mat, 41, 42 bsxfun, 84
.png, 135 case, 72
:, 14 catch, 72
;, 33 cd, 39
=, 26 cellfun, 63
==, 93 chi2cdf, 149
@, 62 chi2pdf, 149
[ ], 95, 108, 110 clear, 29
%, 23 close, 46, 135
%%, 146 continue, 72
&, 94 cumprod, 35
&&, 94 cumsum, 35
{ }, 59
|, 94 datenum, 17
||, 94 datestr, 17
disp, 24
abs, 35 doc, 25, 119, 131
addpath, 38
Algorithm, 122 else, 69
elseif, 69 isnumeric, 95
end, 55, 66, 68
exp, 35, 83 legend, 138
linspace, 57
false, 22, 56, 92, 93, 95 log, 35, 83
figure, 132, 134 logical, 96
fmincon, 123 lookfor, 25
fminsearch, 123
for, 62, 66, 67 max, 35
format, 16 MaxIter, 122
format compact, 24 mean, 35
format long, 16 min, 35
format loose, 24 NaN, 15, 44, 95, 98
format short, 16 nargin, 111
fprintf, 24, 45 nargout, 111
help, 25 normcdf, 149
hist, 132 normpdf, 149
hold, 138 num2cell, 61
num2str, 19
if, 68, 69, 72
ifelse, 68, 69 ones, 58
in, 106 open, 135
Inf, 44 optimset, 122
inv, 86 plot, 132
isempty, 95 prod, 35
isequal, 95 pwd, 39
islogical, 95
isnan, 95 quadprog, 123
rand, 77 TolFun, 122
randi, 77 tpdf, 149
randn, 75 true, 22, 56, 92, 93, 95
regexp, 20 try, 72
regexpi, 20
repmat, 58 var, 35
reshape, 53 vertcat, 150
return, 72 which, 31
rng, 78 while, 67
saveas, 46, 135 xlabel, 133
scatter, 132 xlsread, 43
set, 137 xlswrite, 43
sign, 35
size, 52 ylabel, 133
sqrt, 35 zeros, 58
strcat, 19
strcmp, 22, 93
sub2ind, 150
subplot, 136
sum, 35, 96
switch, 72
tblread, 45
tblwrite, 45
tcdf, 149
tic, 150
title, 133
toc, 150

You might also like