Professional Documents
Culture Documents
Part 1
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
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
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
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
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
13 Extensions 150
1 Basics
1.1 Goal
1.2 Environment
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
.
Be sure to use round brackets to get the order of calculation as you require.
(1+2)*3
1+(2*3)
.
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.
1.6 NaN
MATLAB uses the placeholder NaN for missing values, which often occur in financial
time series.
NaN
NaN + 1
NaN * 100
.
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.
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
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')
.
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)
.
There are many possible qualifications to string searches. We will only use “wild
card” (anything), .*, “must begin with”, ˆ, and “must end with”, $. For example
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
.
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 % .
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”).
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.
Variables are created by setting the name that you want equal to something (using
“=”). The “something” can be
In this section we concentrate on the first type. The others will follow later (quite
quickly), but the all the same rules apply.
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:
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.
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.
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])
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
.
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;
.
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
.
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.
2 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.
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
.
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).
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).
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
Another example
save ('test', 'x','y') % overwrites
clear x y z
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.
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')
.
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.
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.
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
.
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.
3 Matrices
3.1 Goal
In this section you will learn how to create and handle matrices in MATLAB.
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]
.
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
.
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.
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
.
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)
.
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).
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)
.
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
.
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).
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 ... )
.
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.
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
.
4 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).
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
.
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.
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
.
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.
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.
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).
5 “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.
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)
.
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
.
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.
6 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.
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.
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
.
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.
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.
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.
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.
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')
.
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'
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.
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.
7.3 Logic
We will normally only use the last three in the table above - they work for scalars
and matrices.
There are variety of useful checks that can be carried out on MATLAB matrices. For
example
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.
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
.
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
.
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.
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
.
8 Functions
8.1 Goal
In this section you will learn how to create and use 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
.
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.
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.
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)
.
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
.
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).
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
.
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.
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
.
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);
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.
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.
We will do many more complex examples in the applications that follow ...
9 Optimisation
9.1 Goal
This section introduces how to optimise functions in MATLAB. More details will be
added when we look at applications.
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.
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.
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.
[x,fval,exitflag,output] = fminsearch(testfun1,x0)
[x,fval,exitflag,output] = fmincon(testfun1,x0,0,0)
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)
% 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];
.
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])
[x1;x2;x3;x4;x5;x6]
.
EDHEC 2015: MATLAB Part 1 126
Optimisation
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”.
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.
% 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) ;
% change options?
opts = optimset('Algorithm','interior-point-convex');
[ x , ~ , exitflag ] = quadprog(H,[],[],[],Aeq,beq,l,[],[],opts)
.
10 Basic Charts
10.1 Goal
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.
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')
.
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
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.
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);
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');
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
.
11 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!
11.2 Basics
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
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.
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.
12 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.
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)')
13 Extensions
A variety of interesting and advanced topics were not covered above. These include
the following.