Introduction Tom at Lab
Introduction Tom at Lab
Introductory Course to
Matlab with Financial Case
Studies
Panayiotis Andreou
P repared by: PhD Candidate
PBA UCY
1
3.2 Creating 3D Graphs.....................................................................59
3.2.1 Creation of 3D Line Plots ........................................................59
3.2.2 Creation of 3D Mesh and Surface Graphs.................................59
3.2.2.1 Examination of a Functions Critical Points.........................65
4. Control Flow ....................................................................................68
4.1. Logical and Relational Operators..................................................68
4.1.1 The any and al l Functions.......................................................70
4.2. Conditional Statements ...............................................................71
4.2.1 The i f Statement.....................................................................72
4.2.2 The swi tch Statement .............................................................73
4.3. Loop Expressions........................................................................73
4.3.1. The for Loop..........................................................................74
4.3.2. The while Loop......................................................................74
4.3.3. Nested Conditional and Loop Expressions................................75
4.3.4. Additional Control Flow Statements ........................................75
5. m-files: Scripts and Functions ...........................................................77
5.1 m-files: Functions ........................................................................77
5.1.1 Basic Parts of a Function ........................................................79
5.1.1.1 Function Definition Line....................................................79
5.1.1.2 The H1 Line .....................................................................81
5.1.1.3 The Help Text ...................................................................81
5.1.1.4 The Body Text ..................................................................82
5.2 Scripts........................................................................................82
6. Cells and Structures.........................................................................85
6.1 Cells ...........................................................................................85
Cell indexing..................................................................................86
Content indexing............................................................................87
6.2 Structures...................................................................................89
Building structure arrays using assignment statements.....................90
Building structure arrays using the struct function ...........................91
7. Entering and Saving Data Files..........................................................94
7.1. Reading Text ASCII Files: The load command ................................94
7.2 Saving Text ASCII Files: The save command ...................................96
7.3 Other Reading and saving commands............................................97
8. Case Studies....................................................................................98
8.1 The Black Scholes- Merton Options Pricing Formula.....................98
8.1.1 Implementation of the BSM Formula........................................99
8.1.2 BSM Derivatives................................................................... 101
8.1.3 BSM Plots and Surfaces........................................................ 102
8.1.4 BSM Implied Volatility .......................................................... 102
8.2 Function Minimization and Plots................................................. 105
8.3 Portfolio Optimization................................................................. 112
References......................................................................................... 118
2
First Section
1. Introduction
This handout demonstrates a comprehensive introduction to the basic
utilities of a high technical programming language encapsulated under the
computing environment of Matlab. It was prepared based on version 6.5
Release 13, but since it does not have many differences from previous ones,
it can also operate for older versions as well. Upon reading it, you will be in
a position to create programming code to solve elementary (or even
intermediate) financial problems. It has been prepared for postgraduate
students registered for the Master in Finance program offered by the
Department of Business and Public administration University of Cyprus.
3
Matlab features a family of add-on application-specific solutions called
toolboxes. A toolbox is a comprehensive collection of Matlab functions (M-
files) that extend the Matlab environment to solve particular classes of
problems. For example, the Financial Toolbox includes ready to use
functions that provide a complete integrated computing environment for
financial analysis and engineering. The toolbox has everything you need to
perform mathematical and statistical analysis of financial data and display
the results with presentation-quality graphics. With MATLAB and the
Financial Toolbox, you can: compute and analyze prices, yields, and
sensitivities for derivatives and other securities, and for portfolios of
securities; analyze or manage portfolios; design and evaluate hedging
strategies and many more.
4
It is better to use this handout in direct use with the Matlab. It will be more
beneficial if while reading these notes you sit in front of a PC and type the
various commands and execute the given examples.
Although the Matlab package includes extensive help facilities that can be
viewed via a very user-friendly Help Browser, if it is needed, you can also
find additional online (through Internet) help at the following electronic
address:
http://www.mathworks.com/access/helpdesk/help/helpdesk.shtml
or at:
http://wwwhost.cc.utexas.edu/math/Matlab/Manual/ReferenceTOC.html
Moreover, various download, trials and the Matlab Central File Exchange
that contains hundreds of files contributed by users and developers
of Matlab and related products can be found at:
http://www.mathworks.com/web_downloads/
Additionally, any functions that have been created for examples and all
those that are needed to work with the case studies are located in the folder
named as: Matlab Examples (for further details send me an email or ask
during the class).
benjamin@avacom.net.
5
1.2 Basic Definitions
Before moving to the introduction of issues specific to Matlab, some very
basic definitions on computers and programming should be set forth. These
include:
General [1]
bit (short for binary digit) is the smallest unit of information on a
computer. A single bit can hold only one of two values: 0 or 1. More
meaningful information is obtained by combining consecutive bits
into larger units, such as byte.
byte consists a unit of 8 bits and is capable to hold a single character.
Large amounts of memory are indicated in terms of kilobytes (1024
bytes), megabytes (1024 kilobytes), and gigabytes (1024 megabytes).
data is information represented with symbols such as numbers,
words, images, etc.
command is a collection of programming words that instruct the
computer to do a specific task.
algorithm is a set of commands that aim to solve a predetermined
problem.
program is the implementation of the algorithm suitable for
execution by a computer.
variable is a container that can hold a value. For example, in the
expression: z+a, both z and a are variables. Variables can hold both
numerical data (e.g. 10, 98.5) and characters or strings (e.g. 'd' or
'pba').
constant is a value that never changes. It can be a numeric, a
character or a string.
bug is an error in a program, causing the program to stop running,
not to run at all or to provide wrong results. Some bugs can be very
subtle and hard to find. The process of finding and removing the bugs
is called debugging.
6
m-file is a file that contains Matlabs language code. m-files can be
functions that accept arguments and produce output, or they can be
scripts that execute a series of Matlab statements. For Matlab to
recognize a file as an m-file, its file name extension must be *.m.
functions are m-files that can accept input arguments and return
output arguments. The name of the m-file and the calling syntax
name of the function should be the same. Functions operate on
variables within their own workspace, separate from the workspace
you access at the Matlab command prompt. Functions are useful for
extending the existing Matlab language for personal applications (e.g.
create a function that returns the expected return and standard
deviation related with a set of companies).
scripts can operate on existing data in the workspace, or they can
create new data on which to operate. Although scripts do not return
output arguments, any variables that they create remain in the
workspace, to be used in subsequent computations. In addition,
scripts can produce graphical output using functions. Scripts are
useful for automating a series of steps that are needed to be
performed many times (e.g. to create a script that executes a series of
functions related to portfolio optimization).
Every variable has a name and a data type. With Matlab, accepted
variables names do not start with symbols (like ~, +, -) or numbers,
use lower and upper case letters do not exceed 63 characters and do
not resemble reserved words and build-in functions. Acceptable
definitions include: Time, x, y, XYZ, Ray_value, U3e23 etc. Non-
acceptable definitions are the followings: +Time, 3587num, _XYZ,
rayX-values, for, end, while, case, day etc. The data type is a
classification of particular type information. Among the most usable
types are: integer a whole number, a number without any fraction
(e.g. 12, 10, 89); floating point a number with a fractional part (e.g.
25.7, 78,1, 0.000005, 5e-5 which is equal to 5*10-5); and character
readable text character (e.g. 'k'). With Matlab, it is not need to type or
declare variables used in the m-files. Any operation that assigns a
value to a variable creates the variable, if needed, or overwrites its
current value, if it already exists.
7
Every build in or user made function has a calling syntax that is
unique for each function. In Matlab, to call a function you type the
functions name and you enclose the input arguments in brackets (if
more than one input argument exist, then commas should be used to
separate the expressions).
Matlab is handled through the use of various windows, that each is
related with a certain utility. For example, the Command Window is
used to enter variables and run functions and m-files, the Command
History Window makes a diary with the commands that you have
recently entered in the command window, the Workspace Browser
allows you to view the variables that are stored in the workspace, etc.
Any reference to such windows that is made in the main body of
these notes will be explained in detail if it is needed.
8
numbered in square brackets (e.g. [2] is the Matlab online help facilities; see
the section with the references). Additionally, if a figure or a table heading
that has a superscript number enclosed in square brackets will indicate the
source from where it was copied (for instance, Figure[2] X: Figure heading,
indicates that the current figure was copied from Matlab online help
facilities).
Matlab and looks like ) and double click on it. After few
moments, the Matlab starts up and the following sentence appear
in one of the screens:
Step #3: The Matlab is now ready to be used (if you want to quit
Matlab, from the window named as Command Window either type
qui t or exit from the toolbar choose: File > Exit Matlab).
9
Figure[2] 1: The Matlab desktop
The above is termed as the Matlab Desktop (graphical user interfaces) and
contains tools for managing files, variables, and applications associated with
Matlab. Think of the desktop as your instrument panel for Matlab. The
toolbar in the Matlab desktop provides easy access to frequently used
operations. Hold the cursor over a button and a tooltip appears describing
the item. Note that some of the tools also have toolba rs within their windows
[2].
You can change the way your desktop looks by opening, closing, moving,
and resizing the tools in it. Use the View menu to open or close the tools.
You can also move tools outside the desktop or move them back into the
desktop (docking). All the desktop tools provide common features such as
context menus and keyboard shortcuts. You can specify certain
characteristics for the desktop tools by selecting Preferences from the File
menu. For example, you can specify the font characteristics for command
10
window text. For more information, click the Help button in the Preferences
dialog box [2].
Additionally, two more windows that can be seen in Figure 1 can help the
user during the programming time. The first one and most important is the
workspace browser (Figure 2). The Matlab workspace consists of the set of
variables (named arrays) built up during a Matlab session and stored in
memory. You add variables to the workspace by using functions, running m-
files, and loading saved workspaces.
The workspace is not maintained after you end the Matlab session. To save
the workspace to a file that can be read during a later Matlab session, select
Save Workspace As from the File menu.
Another useful window, is the command history (Figure 3). Statements you
enter in the Command Window are logged in the Command History. In the
Command History, you can view previously run statements, and copy and
execute selected statements.
11
Select one or more lines
and right -click to copy
and re-use the command
with the command
window, to evaluate it or
to create an m-file
To activate or close these and some other windows, choose View from the
toolbar. In the following few subsections, the most basic from this screen are
documented.
5+6/12+9/3-21
12
Figure 4: A basic calculation
The Matlab displays the results into a variable named as ans. This is a
default variable name that is used by the command window to display the
most recent results instructed by the user that has not defined a specific
name. Continue by entering the following command that creates a four-
element vector (Figure 5):
[1 2 3 4]
13
The square brackets [ ] indicate the definition of the vector. Also, the space
between the vector numbers separates the vectors elements. The comma ,
is another way of separating the elements. Additionally, note that the default
variable ans has lost its previous value in order to store the results of the
most recent operation.
M=magi c(3)
and after pressing [Enter] you get the Matlabs result (Figure 6):
The magic square is created using the element function magi c that is
already built in Matlab.
14
Type also the following:
x=[(2^2+1)^2-15/4*6.1, 1.23e-2]
and after pressing [Enter] you get the Matlabs result (Figure 7)
Observe that the very first command that you have entered in the command
window has vanished with the additional of the last one (of course it
depends on the size of the window, in here the command window is
minimized so earlier commands vanish too quickly). You can use the scroll
bar on the right to navigate the command window and go up to see the
earlier commands (or view them via the command history window).
Matlab calculates the quantities as follows:
First come the quantities in brackets
Power calculation follow: (e.g. 5 + 2^2 = 5 +4 = 9)
15
* and / follow by working from left to right: (e.g. 2*8/4 = 16/4 = 4)
+ and - follow last, from left to right: (e.g. 6-7+2= -1+2 = 1)
Trigonometric Exponential
s in Sine. e xp Exponential
s i nh Hyperbolic sine. Log Natural logarithm.
as i n Inverse sine. l og10 Common (base 10) logarithm.
as i n h Inverse hyperbolic sine. l og2 Base 2 logarithm and dissect floating
cos Cosine. pow2 Base 2 power and scale floating point
cos h Hyperbolic cosine. re al pow Power that will error out on complex
acos Inverse cosine. re al l og Natural logarithm of real number.
acos h Inverse hyperbolic cosine. re al s qrt Square root of number greater than or
t an Tangent. s qrt Square root.
t an h Hyperbolic tangent. ne xt pow2 Next higher power of 2.
at an Inverse tangent.
at an 2 Four quadrant inverse Complex
tangent.
at an h Inverse hyperbolic tangent. abs Absolute value.
sec Secant. angl e Phase angle.
Construct complex data from real and
s e ch Hyperbolic secant. compl e x
imaginary parts
as e c Inverse secant. conj Complex conjugate.
as e ch Inverse hyperbolic secant. i mag Complex imaginary part.
cs c Cosecant. re al Complex real part.
cs ch Hyperbolic cosecant. unwrap Unwrap phase angle.
acs c Inverse cosecant. i s re al True for real array.
acs ch Inverse hyperbolic cosecant. cpl xpai r Sort numbers into complex conjugate pairs
cot Cotangent.
cot h Hyperbolic cotangent. Rounding and Remainder
acot Inverse cotangent. fi x Round towards zero.
Inverse hyperbolic
acot h fl o o r Round towards minus infinity.
cotangent.
cot h Hyperbolic cotangent. ce i l Round towards plus infinity.
acot Inverse cotangent. round Round towards nearest integer.
Inverse hyperbolic
acot h mod Modulus (signed remainder after
cotangent.
re m remainder after division.
s i gn Signum.
Table 1: The elementary build-in functions
Matlab can handle three different kinds of numbers: integers, real numbers
and complex numbers (with imaginary parts). Moreover, it can handle non-
number expressions like: NaN (Not-a-Number) produced from
mathematically undefined operations like: 0/0, * and i nf produced by
16
operations like 1/0. Matlab as a calculator includes a variety of build-in
mathematical functions like: trigonometric, exponential, complex, rounding
and remainder, etc. Table 1 below, depicts these elementary mathematical
build-in functions (to learn how to use these commands, review the Matlab
help facilities located in section 1.5.3).
Note the build-in functions exhibited in Table 1 have their own calling syntax.
For example, if you type si n in the command window, Matlab returns the
following error massage:
si n(5)
ans =
-0.9589
In the rest of this handout, only the name of the build in functions will be
given. Beside some exceptions where the correct calling syntax of a function
is fully tabulated, the user is responsible in knowing the necessary input
arguments to the function. Additional the use of the command window will
be apparent as you read this manuscript since the learning of a computer
programming language is pure a learning by doing process.
17
List of Useful Commands:
w ho Lists current variables located in the workspace.
whos A long form of who. It lists all the variables in the
current workspace, together with information about their
size, bytes, class, etc.
cl e a r Clear variables and functions from memory.
home Moves the cursor to the upper left corner of the command
window and clears the visible portion of the window. Use
the scroll bar to see what was on the screen previously.
cl c Clears the command window and homes the cursor.
qui t Terminates Matlab.
format short
and afterwards:
for retrieving the x vector that you have created before to get:
x =
2.1250 0.0123
Note that with this format only 4-decimals place are being used (in total 5
digits). Try also the following format commands to see what you get:
18
format l ong e Floating-point format with 15 digits.
Suppressing Output
If you simply type a statement and press [Enter], Matlab automatically
displays the results on screen. However, if you end the line with a semicolon
; Matlab performs the computation but does not display any output [2].
This is particularly useful when you generate large matrices. For example,
A = magi c(100);
will perform two commands the one after the other. In here, after creating
the 100-by-100 magic square that is stored in the A (matrix) variable, matrix
B is created to hold the same values as with A. Additionally, note that if two
or more statements are separated with commas, Matlab will display the
results in the screen in the order that these statements were entered.
to get:
19
s =
0.65321
Blank spaces around the =, +, and -operators are optional, but they
improve readability.
rho = (1 + sqt(5))/2
Instead of retyping the entire line, simply press the key. The statement
you typed is redisplayed. Use the key to move the cursor over and insert
the missing r. Repeated use of the key recalls earlier lines. Typing a few
characters and then the key finds a previous line that begins with those
characters. You can also copy previously executed statements from the
command history window [2].
Current Directory
On the command window toolbar, the user can find the current directory
address bar. Matlab file operations use the current directory and the search
path as reference points. Any file you want to run must either be in the
20
current directory or on the search path (the search path is a default list of
paths that include all folders with Matlab build in functions and toolboxes; to
access this window from the command window go: File>Set Path). A quick
way to view or change the current directory is by using the current directory
field in the desktop toolbar as shown in Figure 8. To search for, view, open,
and make changes to Matlab - related directories and files, use the Matlab
1.5.2 Editor/Debugger
Use the Editor/Debugger to create and debug m-files, which are programs
you write to run Matlab functions [2]. The Editor/Debugger provides a
graphical user interface for basic text editing, as well as for m-file debugging
(Figure 9).
21
Its like a text editor (e.g. MS Word) suitable for writing executable Matlab
code. Notice that reserved words (e.g. whi l e , i f, e l se , e nd, functi on etc)
appear in blue styling whilst accompanied comments in the programming
code (that can be placed after the comments symbol: %) appear in green
letters [2]. Exploit the various menus to become familiar with this window.
For example, by selecting: File>New you can create a new m-file or by
selecting: Debug>Run you can run a saved script that includes various
commands and functions.
help Command
In first place, if the user knows the topic in which an informative help tip is
needed it can use the he l p command. For instance, if help is needed about
the magic squares, the user types the following expression in the command
window:
he l p magi c
and after pressing the [Enter] key, the Matlab response is (Figure 10):
22
Type also:
he l p e l fun
The problem with the he l p command is that the user must be familiar with
the topic under consideration and the word following the he l p command
must be exact and spelled correctly. For example, the Matlab function that
returns the inverse of a matrix is named as: i nv (type help inv to see what
you will get). If the user types inverse or inverce instead, then Matlab
help will return that such functions cannot be found.
lookfor Command
A more flexible command for perusing help from Matlab, is the l ookfor. If the
user is not familiar with the exact help that is looking, it can use the lookfor,
which looks for the given string in the first comment line of the help text in
all m-files located in Matlabs toolboxes. For example, type:
l ookfor inverse
and Matlab returns all m-files functions that contain in their introductory
comments the word inverse. Among them, the user can locate the correct
name for the inverse function (which is simply: i nv) and with the he l p
command can see in detail what this command does. Note that the l ookfor
command is time consuming and sometimes takes up to some minutes to
come up with a result.
23
Figure[2] 11: Matlabs help browser
24
Second Section
Matlabs command:
>> y=[ 5 exp(2) sign(-5) sqrt(9) pi]
Matlabs response:
y=
5 7.3891 -1 3 3.1416
Note that the definition of the row vector, the user it free to use any built-in
function as long as this is used properly. In the above definition, e xp is the
exponential, si gn returns the sign, sqrt is the square root and pi represents
p. General speaking and except some special cases, when a function is
applied to a 1-by-1 scalar, the result is a scalar, when applied to a row or
column vector is a row or column vector and when applied to a matrix the
output is again a matrix. This happe ns because Matlab applied the build-in
25
functions element-wise. The l e ngth of the above vector is obtained via the
following command:
Matlabs command:
>> length(y)
Matlabs response:
ans =
Note that l e ngth is a build-in function that given a vector, it returns its
length. Since the result of this function is not stored in a user-defined
variable, Matlab saves the result in the ans variable. If it is need to save the
vectors length to a variable named Yl e ngth the command would be:
Matlabs command:
>> Ylength=length(y)
Matlabs response:
Ylength =
Matlabs command:
>> a=[-1 2 -3]; b=[2 1 2];
>> c=5*a
Matlabs response:
c=
-5 10 -15
Comments:
An element-by-element multiplication of vector a by 5.
26
Matlabs command:
>> c1=5+b
Matlabs response:
c1 =
7 6 7
Comments:
An element-by-element addition of vector b with 5.
Matlabs command:
>> d=a+b
Matlabs response:
d=
1 3 -1
Comments:
An element-by-element addition of two equal length vectors.
Matlabs command:
>> e=[2*a, c, d]
Matlabs response:
e=
-2 4 -6 -5 10 -15 1 3 -1
Comments:
A larger vector is created after certain manipulations.
Matlabs command:
>> e(2)=-99; e(4)=-99; e(6)=-99;
>> e
Matlabs response:
e=
-2 -99 -6 -99 10 -99 1 3 -1
27
parts of vectors (afterwards, with matrices, the colon can be used to view a
certain part of a matrix). For instance, the following commands produce
three different row vectors:
Matlabs command:
>> v1=1:8, v2=-4:2:2, v3=[0.1:0.2:0.6]
Matlabs response:
v1 =
1 2 3 4 5 6 7 8
v2 =
-4 -2 0 2
v3 =
0.1 0.3 0.5
The careful viewer should have notice that the vector creation via the use of
the colon notation has the form: starting_value:step:finishing_value. The
starting_value consists the first value/element of the vector, the
finishing_value is the last value/element of the vector and all other elements
differ by a value equal to step. Also, when the interval between
finishing_value and starting_value is not divisible by the step, the last value
of the vector is not the finishing_value (i.e. in v3 the last element is 0.5 and
not 0.6). The colon notation is also used to view or extract parts of a vector.
See the examples to get an idea.
Matlabs command:
>> v4=v1(2:4)
Matlabs response:
V4 =
2 3 4
Comments:
Extracting the 2th, 3rd and 4th elements of v1.
Matlabs command:
>> v1(2:3:8)
Matlabs response:
ans =
2 5 8
Comments:
Extracting the 2th, 5th and 8th elements of v1.
28
2.1.2 Column Vectors
Column vectors are created via the use of semi-colon ; instead of commas
and spaces. Operations with column vectors are similar as with row vectors.
The following examples depict the manipulation of column vectors.
Matlabs command:
>> cv=[1;4;7;9]
Matlabs response:
cv =
1
4
7
9
Comments:
Creating a four-element column vector.
Matlabs command:
>> length(cv)
Matlabs response:
ans =
4
Comments:
Taking the vectors length.
Matlabs command:
>> CV=[cv(1:2)+2; cv(2:3)*5]
Matlabs response:
CV =
3
6
20
35
Comments:
Creating CV that is a four-element column vector. Its first two
elements are the two first elements of cv increased by 2 whereas
the last two elements are the 2nd and 3rd elements of cv multiplied
by 5.
29
2.1.3 Transporting Vectors
Matlabs command:
>> z1 = [2 -1 3], z2 = z1', z3 = z2'''
Matlabs response:
z1 =
2 -1 3
z2 =
2
-1
3
z3 =
2 -1 3
Comments:
z1 is a three element row vector. z2 is the transpose of z1. z3 is
similar with z1 since after transposing z2 three times is similar as
transposing once the z2.
Matlabs command:
>> z1'+z2, z1+z2
Matlabs response:
ans =
4
-2
6
Note that that Matlab can store empty vectors. This is done as follows:
30
Matlabs command:
>> Z=[], Z=1:3, Z=[], length(Z)
Matlabs response:
Z=
[]
Z=
1 2 3
Z=
[]
ans =
0
Comments:
Definition of an empty vector.
Empty vector operation is usually used in cases where the user wants to
turn a non-empty vector to an empty one (to reset all the elements of a
vector).
u1
u
w = [ w1 , w 2 ,..., wt1 ] , u = 2
~ ~
M
ut
31
The inner product is defined as the linear combination:
t
~u
w ~=
wi u i
i =1
Matlabs command:
>> w=[1 0 2 -1]; u=[2; 4; -2; 0.5];
>> prod1=w*u, prod2=(2+w)*(u/2), prod3=w*w', prod4=w*u*w*u
Matlabs response:
prod1 =
-2.5
prod2 =
3.25
prod3 =
6
prod4 =
6.25
Comments:
Producing the inner product of various operations. For example
prod1 is computed as: prod1=(1*2)+(0*4)+(2*(-2))+((-1)*0.5)=-2.5.
~u
w~T = [ w u , w u ,..., w u ]
1 1 2 2 2 2
32
The dot product in Matlab is performed via the .* symbol. By the use of dot
product we can get the inner product. This is explained in the following
examples:
Matlabs command:
>> dprod1=w.*u', dprod2=u'.*u'.* w
Matlabs response:
dprod1 =
2 0 -4 -0.5
dprod2 =
4 0 8 -0.25
Comments:
Producing the dot product of various operations. For example
dprod1 is computed as: dprod1=[1*2, 0*4, 2*(-2), (-1)*0.5].
Matlabs command:
>> inner1=sum(w.*u'), inner2=sum((2+w).*(u'/2))
Matlabs response:
inner1 =
-2.5
inner2 =
3.25
Comments:
Producing the summation of dot product of various operations.
When the sum function is used with a dot product, the result is
the inner product of that operation.
In vector manipulations, dot product is performed after dot power (see the
following section).
33
Matlabs command:
>> d_div1=-3:1.5:3, d_div2=1:5
>> d_div2./d_div2, d_div1./d_div2, d_div2./5
Matlabs response:
d_div1 =
-3.0000 -1.5000 0 1.5000 3.0000
d_div2 =
1 2 3 4 5
ans =
1 1 1 1 1
ans =
-3.0000 -0.7500 0 0.3750 0.6000
ans =
0.2000 0.4000 0.6000 0.8000 1.0000
Comments:
Examples of dot division.
Matlabs command:
>>d_div2./d_div1
>> d_div2(3)=0; d_div1./d_div2
>> 1/d_div1
Matlabs response:
Warning: Divide by zero.
(Type "warning off MATLAB:divideByZero" to suppress this
warning.)
ans =
-0.3333 -1.3333 Inf 2.6667 1.6667
ans =
-3.0000 -0.7500 NaN 0.3750 0.6000
34
and a Not-a-Number, NaN, is returned in the vector. In the third
case, the inverse of each vector element is required, but Matlab
returns an error since for such operation the ./ and not /
should have been used instead.
e x e x
lim
x e x + e x
Matlabs command:
>>x=[0.5 1 5 25 50 100 300];
>>(exp(x)-exp(-x))./(exp(x)+exp( -x))
Matlabs response:
ans =
0.4621 0.7616 0.9999 1.0000 1.0000 1.0000 1.0000
Comments:
Apparently, the limit converges to unity.
The dot power of vectors works in a similar way as with other dot products.
Usually there is the need to square (or to rise to some other power) the
elements of a vector. This can be done with the dot power operation as
explained in the following example set.
Matlabs command:
>> d_power=sqrt(0:log(3):6)
>> d_power.^2, d_power.^4, d_power.* d_power, ans.*ans
Matlabs response:
d_power =
0 1.0481 1.4823 1.8154 2.0963 2.3437
ans =
0 1.0986 2.1972 3.2958 4.3944 5.4931
ans =
0 1.2069 4.8278 10.8625 19.3112 30.1737
ans =
0 1.0986 2.1972 3.2958 4.3944 5.4931
ans =
0 1.2069 4.8278 10.8625 19.3112 30.1737
35
Comments:
Examples of dot power. The second or the forth power of a certain
vector can be defined either with the dot power or the dot product
operation.
Before leaving this section, the reader should note that dot power of vectors
is performed before any other operation, followed by the dot product and the
dot division. Off course, if a complex vector command involves
manipulations into brackets, these are executed before any other action.
Use the he l p facilities to see how these functions can be used. The following
illustrate the use of some of these functions.
Matlabs command:
>> clear; clc;
>> x=[ ]; isempty(x)
>> x=linspace(1, 10, 6), x=logspace(0.1, 0.5, 6); x(7)=0.1; x
>> sort(x), cumsum(x), [Max, I]=max(x), x(end)
36
Matlabs response:
ans =
1
x=
1.0000 2.8000 4.6000 6.4000 8.2000 10.0000
x=
1.2589 1.5136 1.8197 2.1878 2.6303 3.1623 0.1000
ans =
0.1000 1.2589 1.5136 1.8197 2.1878 2.6303 3.1623
ans =
1.2589 2.7725 4.5922 6.7799 9.4102 12.5725 12.6725
Max =
3.1623
I=
6
ans =
0.1000
Comments:
Examples with vector functions. The first command instructs for
the creation of an empty vector. The i se mpty function returns 1
for the true statement of an empty vector. Afterwards, l i nspace is
used to generate a row vector of 6 linearly equally spaced points
between 1 and 10 whereas l ogspace is used to generate a row
vector of 6 logarithmically equally spaced points between decades
10^0.1 and 10^0.5. x(7)=0.1 instructs for the creation of a
seventh element for the x vector. sort(x) sorts the elements of x
in ascending order, cumsum(x) is a vector containing the
cumulative sum of the elements of x, [Max, I]=max(x) returns in
Max the maximum value of the vector x and in I the index of the
maximum element. The last command, x( e nd) returns the last
element of the x vector.
a a 12 a 13 a 14
A 2 4 = 11
a 21 a 22 a 23 a 24
37
It is obvious that the above matrix can be decomposed to either 2 row
vectors of 1 4 dimensions or to 4 column vectors of 2X 1 . So, row and
column vectors are special cases of a two dimensional array (matrix).
If we let, a 11 = 1 , a 21 = 2 , a 12 = 2 , a 22 = 2 , a 13 = 5 , a 23 = 4 ,
1 2 5 3
A 2 4 =
2 2 4 1
The subscripts in each element of the matrix denote the elements position.
For instance, the position of a 23 is 2nd row, 3rd column. Matlab stores
matrices using this rational. Having in mind that a two dimensional array is
a composition of row vectors, we can use spaces (or commas) to define its
row vectors and semicolons to separate them. The above matrix can be
easily created as follows:
Matlabs command:
>> A=[ 1 -2 5 -3; -2 2 4 1]
Matlabs response:
A=
1 -2 5 -3
-2 2 4 1
Comments:
Creation of a 2-by-4 matrix.
To show that row and column vectors are special cases or a two dimensional
array (matrix) elaborate on the following exampl es:
Matlabs command:
>> B=linspace(1, 4, 5); C=1:5; D=[-4:-1, NaN, Inf 1];
>> A1=[B; C], A2=[A1; A1], A3=[B -9 -5;D]
Matlabs response:
A1 =
1.0000 1.7500 2.5000 3.2500 4.0000
1.0000 2.0000 3.0000 4.0000 5.0000
38
A2 =
1.0000 1.7500 2.5000 3.2500 4.0000
1.0000 2.0000 3.0000 4.0000 5.0000
1.0000 1.7500 2.5000 3.2500 4.0000
1.0000 2.0000 3.0000 4.0000 5.0000
A3 =
1.0000 1.7500 2.5000 3.2500 4.0000 -9.0000 -5.0000
-4.0000 -3.0000 -2.0000 -1.0000 NaN Inf 1.0000
Comments:
Various manipulations with matrices.
The examples above, illustrate the case where a larger matrix can be created
from smaller ones. Also, pay attention that Matlab returns an error if the
user tries to combine row or column vectors with different lengths to create
a two dimensional array.
Matlabs command:
>> [m1 n1]=size(A1); [m2 n2]=size(A2); [m3 n3]=size(A3);
>> M_N=[m1 n1; m2 n2; m3 n3]
Matlabs response:
M_N =
2 5
4 5
2 7
Comments:
Using the si ze function to find the size of various matrices. Each
row of the M_ N matrix contains the size of matrices A1, A2 and
A3 respectively.
a 11 a 21
a
a a 12 a 13 a 14 T 12 a 22
A 2 4 = 11 , A 4 2 =
a 21 a 22 a 23 a 24 a 13 a 23
a 14 a 24
39
It is the same idea with the transpose of a row vector to a column one and
vise versa. The transpose of an m n matrix is an n m one that is found if
the rows of the original matrix become columns in the transposed one.
Recall that the transpose in Matlab is performed with ' . See the following
examples to digest this issue.
Matlabs command:
>> A4=[1 2 3; 4 5 6], size(A4), A4', size(A4'), A5=[A4' A4']
Matlabs response:
A4 =
1 2 3
4 5 6
ans =
2 3
ans =
1 4
2 5
3 6
ans =
3 2
A5 =
1 4 1 4
2 5 2 5
3 6 3 6
Comments:
Exploiting the transpose of a matrix.
1 2 5 3
A 2 4 =
2 2 4 1
done in the following way ( A has already been created and should be stored
40
in the workspace; use the who function to view the variables that you have
saved in the workspace or view them from the workspace browser):
Matlabs command:
>> A(1,2), A(2,3), A(2,4)
Matlabs response:
ans =
-2
ans =
4
ans =
1
Comments:
Extracting specific elements from a matrix.
So, in Matlab, to refer to a certain matrix element, after the matrix name the
elements index/position is enclosed in parenthesis. This is similar with the
indexing of vectors elements with the exception that in the case of matrices,
two indexes should be used (the first one indicates the row number whilst
the second the column number). In general, the syntax for manipulating a
matrix element in Matlab is:
K(row_index, column_index)
41
position (2,1) is taken to be the second (2), the (3,1) the third and finally the
(m, n) element is the last one (n*m). View the following example to
understand this king of matrix indexing.
Matlabs command:
>> H=magic(4), H(1), H(2), H(9), H(16)
Matlabs response:
H=
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
ans =
16
ans =
5
ans =
3
ans =
1
Comments:
Extracting specific elements from a matrix using single indexing.
For matrices, the colon notation : plays an important role. Colon can be
used to extract either a specific part of a matrix, or to view a whole row, a
whole column or a sub-matrix extracted from the original one. Earlier, the
colon was used to define vectors and it has been explained that it creates
elements from a starting_value through a finishing_value equally spaced
according to a defined step (if the step is not defined, then the step is taken
to be 1). In Matlab, a certain row of a matrix can be extracted by placing the
colon in the row_index, K(:,column_index), and a certain column by placing
the colon in the column_index, K(row_index:,:). A sub-matrix that is
composed by the r1 to r2 rows (r1=r2) and c1 to c2 columns (c1=c2) of the
original matrix can be retrieved according to the following syntax:
K(r1:r2, c1:c2)
42
In addition, there are special cases where the step is defined to be a different
integer number other than 1. Some paradigms follow:
Matlabs command:
>> A(:,1), A(1,:), A(:,1:3), A=[A', A'.*2], A(2:3,3:4)
>> A(1:3,1:2)=A(2:end,3:end)
Matlabs response:
ans =
1
-2
ans =
1 -2 5 -3
ans =
1 -2 5
-2 2 4
A=
1 -2 2 -4
-2 2 -4 4
5 4 10 8
-3 1 -6 2
ans =
-4 4
10 8
ans =
-2 -4
A=
-4 4 2 -4
10 8 -4 4
-6 2 10 8
-3 1 -6 2
Comments:
The first command, instructs for the extraction of the first column
whilst the second for the extraction of the first row. The following
one instructs for the extraction of the 1st, 2nd and 3rd columns.
Afterwards, A is re-built; the following command instructs for the
extraction of the sub-matrix that is composed from the elements
of A that are included in: 2nd and 3rd row 3rd and 4th columns.
The following command is a special case where the step in the
colon expression is different than 1. The last command is a more
tricky use of the colon.
43
2.2.2 Matrix Basic Manipulations
Subtraction and multiplication with a scalar are similar as with the vector
case. Matrix dimensions ( si ze ) must match when performing manipulations
with addition and subtraction. Some examples follow:
Matlabs command:
>> J=[-1 2 3 1; 5 2 4 2; 1 1 2 0]; I=[1 4 5 2; 8 7 5 1; -1 1 -1 1];
>> J+2*I, J(:,1)+I(:,2), J(1,:)-1/4*I(2,:)
Matlabs response:
ans =
1 10 13 5
21 16 14 4
-1 3 0 2
ans =
3
12
2
ans =
-3.0000 0.2500 1.7500 0.7500
Comments:
Basic matrix addition, subtraction and scalar multiplication.
44
Matlabs command:
>> clear; U=[-1 2 1; 0 -2 3]; V=[1:3; 5 2 4];
>> U.^2, U.*V, (1./V).^2.*U, U.^U
Matlabs response:
ans =
1 4 1
0 4 9
ans =
-1 4 3
0 -4 12
ans =
-1.0000 0.5000 0.1111
0 -0.5000 0.1875
ans =
-1.0000 4.0000 1.0000
1.0000 0.2500 27.0000
Comments:
Dot operations with two-dimensional arrays.
(m n ) (n l )
That is, the firsts matrix columns equal the seconds rows. A matrix A
with dimensions m n can be multiplied with a matrix B with dimensions
m l resulting to a matrix C with dimensions m l :
Cml = Amn B ml
45
Cm1 = Amn C 1n 1
b11 b12
b b 22
a a 12 a 13 a 14
A 2 4 = 11 , B 4 2 = 21
a 21 a 22 a 23 a 24 b31 b 32
b41 b 42
Like linear algebra, Matlab products with matrices (and/or vectors) are
calculated as follows:
c c
C 22 = A24 B 42 = 11 12
c 21 c 22
That is, the element in the (1,1) position of the new matrix C if the inner
product of the 1st row of A with the 1st column of B, the (1,2) element of
C is the inner product of the 1st row of A with the 2nd column of B and
so on. Work through the following examples to digest this topic.
Matlabs command:
>> clear; A=[ 1 -2 5 -3; -2 2 4 1]; B=[2 3;1 0;2 -1;1 4]; A_B=[A;B'];
>> R1=[-2 -1 3 2]; C1=[1; -1; 2; 0];
>> C=A*B, Row=R1*A_B, Col= A_B*C1, A*(A_B*A_B)*B
Matlabs response:
C=
7 -14
7 -6
Row =
12 5 -10 16
46
Col =
13
4
5
1
ans =
39 -310
297 314
Comments:
Matrix-vector and matrix-matrix products.
Matlabs command:
>> eye(3,2), ones(2,3), diag([2 3; 1 -2]), rand(2,2), zeros(1,2)
Matlabs response:
ans =
1 0
0 1
0 0
ans =
1 1 1
1 1 1
ans =
2
-2
47
ans =
0.9501 0.6068
0.2311 0.4860
ans =
0 0
Comments:
Examples with matrices build-in functions.
Ax = b
48
a 11 x 1 + a 12 x 2 + ... + a 1m x m = b1
a 21x 1 + a 22 x 2 + ... + a 21m x m = b2
M
a n 1 x 1 + a n 2 x 2 + ... + a nm xm = bn
x = A 1b
given that A 1 (that represents the inverse matrix of A ) exists and the
number of equation, n, is equal or greater than the number of unknowns, m.
A unique solution to the above equation system exists when: n=m.
Matlab has standard and efficient specialized routines to solve such systems
like the ml di vi de function (called alternatively with \). Otherwise, a quick
way (but some times non practical and inaccurate if the number of
equations is extremely large) to solve the above system is via the inverse
function, i nv (note that the i nv can be used only with square matrices). View
the following example to understand how you can solve a small system of
linear equations:
Matlabs command:
>> clear; A=[2 4 3; -2 -4 2; 6 4 2]; b=[2 ;4;1];
>> x1=inv(A)*b, x2=A\b
Matlabs response:
x1 =
0.0500
-0.4250
1.2000
x2 =
0.0500
-0.4250
1.2000
Comments:
Two ways for solving a system of linear equations.
49
To see that these two procedures lead to different results, elaborate on the
following example (search online help to see the use of the command:
pascal ):
Matlabs command:
>> clear; A=pascal(10); b=[5; -2; 4; 8; 1; 2; 0; -6; 2; 3];
>> x1=inv(A)*b;, x2=A\b;
>>diff=x1-x2
Matlabs response:
diff =
-1.0328 e-006
9.0204 e-006
-3.4539 e-005
7.6293 e-005
-0.00010781
0.0001013
-6.3407 e-005
2.5521 e-005
-5.9979 e-006
6.2738 e-007
Comments:
For even moderate linear systems, the two methods ( i nv and \)
lead to different solutions. If high precision is required, then the
researcher should prefer the \.
The most proper way for large systems is the use of \. See the help
facilities for details on i nv and on \.
50
Third Section
3. Plots and Graphs (2D and 3D)
It is quite easy to create a plot or a graph by using the variables or
parameters that have already been stored in the Matlabs workspace. Matlab
offers a variety of build-in functions for creating simple two dimensional
plots, 3 dimensional surface plots, to combine plots to a larger one and so
on. The following subsections are a very brief and an elementary reference to
the visualization capabilities of Matlab.
2 x 2 + 5x 1
y=
x3 5
Matlabs command:
>> clear; x=0:0.5:5; y=(2*x.^2+5*x-1)./(x.^3-5); plot(x,y);
>> x=0:0.2:5; ; y=(2*x.^2+5*x-1)./(x.^3-5); plot(x,y);
51
Matlabs response:
-2
-4
-6
-8
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
20
15
10
-5
-10
-15
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Comments:
Plot of a function. The use of dot operations is prominent for this
task. Note that the plots smoothness is controlled by the density
of the x vector. In the second plot where the x is denser, the
function plot is smoother.
52
Figure[2] 10: The figure window
This figure window has tools that look like a photo editor (e.g. Microsoft
Photo Editor). You can select objects in a graph, cut, copy, paste, move and
resize objects, zoom in and zoom out at certain areas of the plot, change the
settings of the axes, print or save the figure for a later use or even to export
the plot in a certain format (e.g. *.emf, *.bmp, *,ipg, *.tif, etc). Create a figure
and play around with the various tools to learn their use.
The plots that are included in this handout (except the ones that were
copied from [2]) have been exported from the figure window in an enhanced
metafile format (*.emf). To export a plot, from the figure window go:
File>Export, and from the window that appears choose the exporting format,
give a name to the file and save it in a folder of your choice. By doing this,
you can easily insert plots from Matlab to a text editor like Microsoft Word.
53
to mark each plotted point with a symbol. To do this, the user should call
the plot function as:
where ? represents the color, ? the mark style and ? the line style (if
not given, then Matlab uses a default style). Table 5 tabulates the plot
facilities (see also the online help).
Moreover, Table 6 lists additional commands that are useful when using the
pl ot function.
Function Comment
axi s Sets the minimum and maximum values of axes.
cl f Clear the current figure.
cl ose (all) Closes the current (all) figure(s).
fi gure Creates a new figure window.
gri d on/off Adds/removes major grid lines to the current axes.
gte xt('text') Adds text to a figure manually, by the use of mouse.
hol d on/off hol d on/off holds the current plot and all axis
properties so that subsequent graphing commands
add to the existing graph.
l e ge nd('text')/l e ge nd off Adds (removes) a legend to the graph.
l ogl og The same as with pl ot but logarithmic scale axes
are used.
se mi l ogx The same as with pl ot with the exception that
logarithmic scale is used for X-axis.
se mi l ogy The same as with pl ot with the exception that
logarithmic scale is used for Y-axis.
subpl ot Breaks the current figure to subplots.
ti tl e ('text') Adds a title above the figure.
xl abe l ('text') X-axis label
yl abe l ('text') Y-axis label
Table 6: Various functions that help in the creation of 2D-plots.
54
View the following examples to digest the plot facilities.
Matlabs command:
>> plot(x, y, 'md: '); figure; plot(x, y, 'r*--'); hold on;
>> y1=rand(1,length(y)), plot(x,y1, 'bo'); plot(x,y1, 'r+');
>> xlabel('X-values'); ylabel('Y-values'); title('This is a plot');
>> close all; plot(x,y, 'bp--', x, log(y1.^2), 'rh', x, log(y1.^2),'bs');
Matlabs response:
20
15
10
-5
-10
-15
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
This is a plot
20
15
10
Y-values
0
-5
-10
-15
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
X-values
55
20
15
10
-5
-10
-15
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Comments:
Experimenting with various functions and facilities related with
the plots. The last pl ot command shows how few plots can be
depicted in one figure without using the hol d on command.
The following examples, concern the creation of some subplots in one figure
window. If you view the online help for the subpl ot command, you will see
that it takes three input arguments. That is, it is called as:
subpl ot(m,n,p)
It breaks the figure window into an m-by-n matrix of small axes, selects the
p-th axes for the current plot, and returns the axis handle. The axes are
counted along the top row of the figure window, then the second row, etc.
The subpl ot function instructs which subplot is handled at the current time.
After the subpl ot command, a pl ot command should follow. See the following
examples:
Matlabs command:
>> close all; subplot(2,3,1); plot(x,y, 'r--'); title('Subplot 1');
>> subplot(2,3,2); plot(x,y1, 'y*'); title('Subplot 2');
>> subplot(2,3,3);
>> subplot(2,3,5); plot(randn(1,30), 'bo:'); title('Subplot 5');
>> subplot(2,3,6); plot(x,y, 'bp--', x, (y1.^2), 'rh', x, log(y1.^2),'bs');
>> title('Subplot 6');
56
Matlabs response:
Subplot 1 Subplot 2
20 1 1
0.8 0.8
10
0.6 0.6
0
0.4 0.4
-10
0.2 0.2
-20 0 0
0 2 4 6 0 2 4 6 0 0.5 1
Subplot 5 Subplot 6
2 20
1 10
0 0
-1 -10
-2 -20
0 10 20 30 0 2 4 6
Comments:
Experimenting with the subpl ot command. The first two input
arguments to the subpl ot function define the dimensionality of the
figure window. If m is the first input arguments and n the second,
then the figure window breaks to an m-by-n plot matrix. The third
input to the subpl ot function designates the current subplot to be
handled. Starting from the upper left corner and moving row-wise to
the lower right corner, 1 refers to the first subplot, 2 to the second
and mn to the last one. After each subpl ot command, the pl ot
command should follow. In the current examples, the commands
instruct for the creation of a 2-by-3 subplot matrix. The 1st, 2nd, 5th
and 6th subplots are used whilst the 3rd and 4th are currently unused.
Note that if the subpl ot command is avoided for any subplot, then its
space on the figure window stays empty. If only the subpl ot is called
as with the case of the third subfigure, then a blank figure appears in
the figure window.
57
where PropertyName relates with an element of the plot and
PropertyValue is defined by the user. Some useful properties concern the
following:
LineWidth - specifies the width (in points) of the line.
MarkerEdgeColor - specifies the color of the marker or the edge color
for filled markers (circle, square, diamond, pentagram, hexagram, and
the four triangles).
MarkerFaceColor - specifies the color of the face of filled markers.
MarkerSize - specifies the size of the marker in units of points.
Matlabs command:
>> plot(x,y,'bd-.', 'LineWidth', 2, 'MarkerSize', 11, ...
'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'g')
Matlabs response:
20
15
10
-5
-10
-15
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Comments:
An example of a plot that uses some of the pl ot properties.
58
3.2 Creating 3D Graphs
Matlab offers fancy 3-dimensional line plots and surface graphs.
Matlabs command:
>> clear; g=linspace(-5*pi,5*pi,200); plot3(sin(g),cos(g),g,'r*-');
>> xlabel('x'); ylabel('y'); zlabel('z'); title('A helix');
Matlabs response:
A helix
20
15
10
0
z
-5
-10
-15
-20
1
0.5 1
0.5
0
0
-0.5
-0.5
-1 -1
y
x
Comments:
Creating a helix with the pl ot3 function.
59
functional expression, z=f(x,y), is evaluated. Usually, we evaluate the z
behavior in a certain area of the (x,y)-plane in which z has some interesting
properties (e.g. it presents a minimum, a maximum or a saddle point).
Suppose that a x vector that defines the x-axis (abscissa) and a y vector that
defines the y-axis (ordinate) exist and define the (x,y)-plane on which we
would like to create the 3D surface of z=f(x,y). To plot the surface, it is
needed to create a grid of sample points (most preferable with high density
and this is defined by the difference between the elements of x and y) that
covers the rectangular domain of the (x,y) plane in order to generate X and Y
matrices consisting of repeated rows and columns of x and y, respectively,
over the domain of the function. Then these matrices will be used to
evaluate and graph the function.
We will see how we can plot a 3D surface via an example. Let say that we
need a graph of the well know peaks function that has the following
functional form:
x 1
Z = f ( x , y ) = 3( 1 x ) 2 e x ( y +1) 10( x 3 y 5 ) e x y e ( x +1) y
2 2 2 2 2 2
5 3
2x 2
4 y 4
60
Matlabs command:
>> clear; x=-2:1:2; y=-4:1:4; [X,Y]=meshgrid(x,y)
>> plot(X,Y, 'rh'); axis([-3 3 -5 5]); xlabel('x-axis'); ylabel('y-axis');
>> title('Meshgrid');
Matlabs response:
X=
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
-2 -1 0 1 2
Y=
-4 -4 -4 -4 -4
-3 -3 -3 -3 -3
-2 -2 -2 -2 -2
-1 -1 -1 -1 -1
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
Meshgrid
5
0
y-axis
-1
-2
-3
-4
-5
-3 -2 -1 0 1 2 3
x-axis
Comments:
Creating the grid necessary for plotting a 3D surface. me shgri d
takes as inputs the vectors x and y that define the (x,y)-plane that
should be used to evaluate Z and returns two matrices ( X and Y)
that if taken together, generate various (x,y) pairs that lay in the
rectangular domain. The subsequent 2D plot of X and Y shows
61
rectangular domain. The subsequent 2D plot of X and Y shows
how the grid is sampled.
Now, we should evaluate the Z at each pair of the grid and generate the
surface plot. This is done with the following code:
Matlabs command:
>> Z =3*(1-X).^2.*exp( -(X.^2) - (Y+1).^2)- ...
10*(X/5-X.^3-Y.^5).*exp( -X.^2-Y.^2)-1/3*exp( -(X+1).^2-Y.^2);
>> figure(1); mesh(X,Y,Z); xlabel('x'); ylabel('y'); zlabel('Z');
>> figure(2); surf(X,Y,Z); xlabel('x'); ylabel('y'); zlabel('Z');
Matlabs response:
0
Z
-2
-4
-6
4
2 2
1.5
1
0 0.5
0
-2 -0.5
-1
-1.5
-4 -2
y
x
62
6
0
z
-2
-4
-6
4
2 2
1.5
1
0 0.5
0
-2 -0.5
-1
-1.5
-4 -2
y x
Comments:
Creating the 3D mesh and a 3D surface. The function is not smooth
because the dense of the x and y was too low.
Matlabs command:
>> x=-2:0.25:2; y=-4:0.5:4; [X,Y]=meshgrid(x,y);
>> Z =3*(1-X).^2.*exp( -(X.^2) - (Y+1).^2)- ...
10*(X/5-X.^3-Y.^5).*exp( -X.^2-Y.^2)-1/3*exp( -(X+1).^2-Y.^2);
>> figure(1); mesh(X,Y,Z); xlabel('x'); ylabel('y'); zlabel('Z'); title('Peaks')
>> figure(2); surf(X,Y,Z); xlabel('x'); ylabel('y'); zlabel('Z'); title('Peaks');
63
Matlabs response:
Peaks
0
Z
-2
-4
-6
-8
4
2 2
1.5
1
0 0.5
0
-2 -0.5
-1
-1.5
-4 -2
y
x
Peaks
0
Z
-2
-4
-6
-8
4
2 2
1.5
0 1
0.5
0
-2 -0.5
-1
-1.5
-4 -2
y x
Comments:
Creating the 3D mesh and a 3D surface with a higher density
meshgrid.
64
To find what other useful commands can be accompanied the me sh and surf
commands, use the online help.
Matlabs command:
>> V=-10:1:10; [c,h] = contour(x,y,Z,V); clabel(c,h), colorbar; hold
on;
>> xlabel('x'); ylabel('y'); title('Contour plot of the peaks function');
Matlabs response:
6
3
1
3 2
2 1 4
2 1 45
6
7 Global Maximum 4 3
0 5 7
6 5
1 3 4 3
-1 2
2 2
-2 1
Local Minimum 2
3
0 0 Local Maximum
y -2 1 2
1 0
3 Local Maximum 2
-1 0
1 -1 1
-1 1 2 -2
0 -4 -3
0-1 -5
Global Minimum 0 -2
-6 -5
-3
-2 -3 -4 -2 -1
-2
-1 -4
-3 0
-4 -6
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
x
65
Comments:
Creating the contour plot of the peaks function. Viewing this plot,
it is easy to identify the critical points of the function. There is
one global maximum, one global minimum, two local maxima and
a local minimum. Additionally, from the color-bar that is created
with the command: col orbar, and from the values printed next to
the contour curves, it is obvious that the peaks functions around
its critical points exhibits a flatness (saddle points) (Note: the *
that indicate a critical point are plotted approximately); the text
next to each critical point was placed with the gte xt command.
Matlabs command:
>> close all; x=-2:0.05:2; y=-4:0.25:4; [X,Y]=meshgrid(x,y);
>> Z =3*(1-X).^2.*exp( -(X.^2) - (Y+1).^2)- ...
10*(X/5-X.^3-Y.^5).*exp( -X.^2-Y.^2)-1/3*exp( -(X+1).^2-Y.^2);
>> V=-10:1:10; [c,h] = contour(x,y,Z,V); clabel(c,h), colorbar; hold
on
>> xlabel('x'); ylabel('y'); title('Contour plot of the peaks function');
>> Fmax=max(max(Z)); P=find(Z==Fmax); xy=[X(P) Y(P)];
>> plot(xy(1),xy(2),'rp', 'MarkerSize',10);
>> text(xy(1)+0.05,xy(2), 'Maximum Point');
Matlabs response:
6
3
1
2 1
3 4 3 4
2 5
2 7
6
0 7 Maximum Point
5 4 3
1 5 6
4 2
1 3 2
2
-1 1 1
-2 0
-3 0 3
0 1 3
y -2 2 2
0
-1
2 3 1
1 2 0 -1
-1 0
1 -2 -4 -3 0
-5
-1 -2
0
-3 -6 -5
-2 -2 -1
-4 -3
-2
-1
-4
-3
0
-4 -6
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
x
66
Comments:
Locating the maximum of the peak function via an exhaustive
search. Fmax=max(max(Z)) stores in F max the maximum value
of the Z matrix that is equal to 7.9966. P=fi nd(Z==Fmax) returns
in P the element index (a single value) where Z is equal to Fmax;
specifically the Z element with index number 1343 has the value
of 7.9966. Finally, in xy we store the x-and-y coordinates of the
maximum point. Marke rSi ze in the pl ot command creates a
lager size mark symbol.
For practice try to write your own code to find the global minimum of the
peaks function (you can also try to find the local minima and maxima but
this is tricky).
67
Fourth Section
4. Control Flow
A collection of commands that include repetition of a conditional code
segment is termed as control flow structure. In Matlab as in any
programming language, control flow commands are presented via the
execution of a conditional expression (e.g. execute a code segment if a
statement is true) that is based on logical and/or relational operators.
In addition, Matlab has (at least) 3 logical operators: & (logical AND), |
(logical OR), and ~ {logical complement - not). If we have two matrices A
and B that share the same dimensionality then:
A & B is a matrix whose elements are 1's where both A and B
have non-zero elements, and 0's where either has a zero element. A
and B must have the same dimensions (or one can be a scalar). For
example in the case of scalars: 1 & 0, 0 & 1 and 0 & 0 will result to 0
(FALSE) while 1 & 1 is 1 (TRUE).
A | B is a matrix whose elements are 1's where both A or B has
a non-zero element and 0's where both have zero elements. A and
B must have the same dimensions (or one can be a scalar). For
68
example and for the case of a scalar: 0 | 1, 1 | 0, and 1 | 1 is 1
(TRUE) while 0 | 0 is 0 (FALSE).
~A is a matrix whose elements are 1's where A has zero elements
and 0's where A has non-zero elements. For example and in the
case of a scalar: ~1 is (FALSE) and ~0 is 1 (TRUE).
Note that for Matlab, any number (integer or real, positive or negative)
different from 0 (zero) is a true statement, that is, it has the same meaning
as with 1. Pay also attention that the precedence with relational and logical
operators is the following (from highest to lowest):
1. Transpose .' , power .^, complex conjugate transpose ' ,
matrix power ^;
2. Unary plus +, unary minus -, logical negation ~;
3. Multiplication .*, right division ./, left division that returns the
inverse of a division .\, matrix multiplication *, matrix right
division /, matrix left division \;
4. Addition +, subtraction ;
5. Colon operator :;
6. Less than <, less than or equal to <=, greater than >, greater
than or equal to >=, equal to ==, not equal to ~=;
7. Element-wise logical AND &;
8. Element-wise logical OR |.
View the examples that follow to digest the use or logical and relational
operators.
Matlabs command:
>> clear all; x=2; y=0; z=-2;
>> a=(x>=1), b=(x~=1 & y), c=(1|y & x>0), d=(~y & z | ~x == 5)
Matlabs response:
a=
1
b=
0
c=
1
69
d=
1
Comments:
Logical and relational operations. a is 1 because the statement
evaluated is TRUE since x is 2 and greater than 1. b is FALSE
because: x~=1 returns 1, and 1 & y returns 0. c is TRUE
because: x>0 is 1, and 1|y & 1 is 1 | 1 which is TRUE. d is
TRUE because: ~y is 1 and ~x is 0 so we have (1 & z | 0==5)
that is equal to (1 & z | 0) that is equal to: 1 | 0 that is TRUE.
Some examples with matrices and the logical and relational operators follow:
Matlabs command:
>> clear all; x=[5 0 -1; 2 4 8]; y=[2 1 -1; 1 2 4];
>> a=(x==5), b=(x~=1 & y), c=(2*y==x | ~x), d=(x>0 | y==1 |x~=x)
Matlabs response:
a=
1 0 0
0 0 0
b=
1 1 1
1 1 1
c=
0 1 0
1 1 1
d=
1 1 0
1 1 1
Comments:
Logical and relational operations with matrices. In a we have only
the first element to be 1 since it the only one that is equal to 5.
We get b to be a TRUE matrix because x~=1 returns a matrix of
1s since none element is equal to 1. By definition, all elements in
y are taken to be TRUE statements. So TRUE & TRUE gives b full
of 1s (Figure out how the c and d were evaluated).
70
matrix, returning a row vector of 1's and 0's. The second one, al l , becomes
TRUE if all elements of a vector are nonzero. For vectors, al l returns 1 if
none of the elements of the vector are zero. Otherwise it returns 0. For
matrices, al l operates on the columns of the matrix, returning a row vector
of 1's and 0's. View the following code to understand these tow functions.
Matlabs command:
>> clear all; z=[-5 2 0]; x=[5 0 -1; 2 4 8]; y=[2 1 -1; 1 2 4];
>> a1=any(z), a2=any(x), a3=any(y), a4=all(z), a5=all(x), a6=all(y)
Matlabs response:
a1 =
1
a2 =
1 1 1
a3 =
1 1 1
a4 =
0
a5 =
1 0 1
a6 =
1 1 1
Comments:
Displaying the use of any and al l .
71
4.2.1 The if Statement
The i f statement evaluates a logical expression and executes a group of
statements when the expression is TRUE. The optional e l se i f and e l se
keywords can be used for the execution of alternate groups of statements.
An e nd keyword, which matches the i f, terminates the last group of
statements. The groups of statements are delineated by the four above
keywords-no braces or brackets are involved [2]. The three possible syntax
versions of this conditional expression are tabulated in Table 7.
Syntax Example
if logical expression flag=1;
Profit=sales*0.17;
end
Table 7: The i f statement syntax and examples.
72
Although is possible to run these examples via the command window, it is
better to use the Matlab Editor/Debugger to write a script instead. Real
examples with the conditional statements as well as with the loops are
postponed until the introduction of scripts in section 5.
Syntax Example
switch expression dice=3;
switch (dice)
case choice #1 case 1
disp('One')
segment of executable programming code case 2
disp('Two')
case choice #2 case 3
disp('Three')
segment of executable programming code case 4
disp('Five')
otherwise
case 5
segment of executable programming code disp('Five')
otherwise
end disp('Six')
end
Table 8: The swi tch statement syntax and example.
73
4.3.1. The for Loop
The for loop repeats a group of statements a fixed, predetermined number of
times. A matching e nd delineates the statements. The syntax for the for loop
is exhibited in Table 9.
Syntax Example
for index=first_value:step:last_value for i=1:10
disp(i)
segment of executable programming code end
end sumj=0;
for j=25:-2:-12
sumj=sumj+j;
end
Table 9: The for statement syntax and example.
The colon notation is similar as in the case of the vectors. Actually, index in
the for syntax is a vector with n elements with first element being the
first_value and last the last_value. The difference between the index
elements is step. Afterwards, the for statement executes n times the segment
of executable programming code moving from the first element of the index
to the last one element-by-element at each time. If step is not displayed,
then by default is set to 1.
Syntax Example
while expression X=-3;
while X<=10
segment of executable programming code
disp(X)
end X=X+1;
end
Table 10: The whi l e statement syntax and example.
74
4.3.3. Nested Conditional and Loop Expressions
All conditional and loop statements can be combined in any way that is
desirable. If for example a loop expression includes an i f statement that
nests a swi tch statement and so on, then, in programming terminology, it is
termed that we have nested statements. As long as the statements are
nested in a logical and a non redundant manner, the user will get correct
answers. View the following example that is exhibited in Table 11 and nests
various statements (figure out their use).
75
Statement Comment
bre ak Terminates the execution of a for or whi l e loop.
Statements in the loop that appear after the bre ak
statement are not executed.
conti nue Passes control to the next iteration of the for or while
loop in which it appears, skipping any remaining
statements in the body of the loop.
t r y ca t ch Changes flow control if an error is detected during
execution.
re turn Causes a normal return to the invoking function or
to the keyboard. It also terminates keyboard mode.
Table 12: Additional control flow statements.
76
Fifth Section
As said, functions and scripts can be created with the use of the Matlabs
Editor/Debugger. You only have to write the command lines, save the file in
a directory of your choice and execute it by typing its name to the command
window and pressing [Enter] (you have to make sure that the Matlabs
current directory and the directory in which you save the file are the same).
Although m-files represent a text file and it is possible to use any text editor
to create a function or a script (as long as the extension of the file is *.m this
can work), it is preferable to use the default editor because: i) when you save
a file it automatically takes the extension *.m, ii) the reserved words like: for,
whi l e , functi on, e nd etc are bl ue colored whilst comments that make the
programming code more readable are green colored, and iii) it automatically
communicates with the command window and allows to run a script via a
command found in the Debug menu (see the menu bar of Editor/Debugger).
77
the theoretical price of a call option contract according to various options
pricing models. Options pricing models like the Black and Scholes, the
Mertons Jumps diffusion, the displaced diffusion model, Hestons
stochastic volatility model, and other can easily be implemented via a
different function.
For the function Di agExtract note the followings: i) if after executing your
function you get an error, then read the error message that it is returned to
the command window (this is very helpful in finding where to look for the
78
error); you have to return to the Editor to debug the error, re-save the
function and try to run it again. If you debug your function or add something,
then you have to re-save the file in order to take place the changes (note that
if unsaved changes are made in a function file, an asterisk (*) appears next
to the function name in the Editors title bar (so in Figure 12, the functions
has not been saved); ii) although the input argument of the function is a
matrix named X and the output is a vector named V , when you call this
function from a script or from the command window, you can give any names
you like. For example in the command window enter:
[DiagElements]=DiagExtract(magic(4))
to see the result; iii) After the function is executed, none of the variables that
were used are save d in the workspace; iv) If after each command line you do
not place the semi-colon ; then when the function is executed, you can
observe in the command window the result of these command lines (this is
useful to be done when you try to debug a function); v) observe on Figure 12
that on the bottom of the Editor/Debugger there is a predefined caption area
that indicates that the current m-file is a function with the name
Di agExtract.
79
(Figure copied from [2])
Matlab function names have the same constraints as variable names. The
name must begin with a letter, which may be followed by any combination of
letters, digits, and underscores. Making all letters in the name lowercase is
recommended as it makes your m-files portable between platforms (of course
the use of upper case assures that the functions names you create do not
resemble any other Matlab function and/or reserved word). The name of the
text file that contains a Matlab function consists of the function name with
the extension .m appended. For example, DiagExtract.m.
If the filename and the function definition line name are different, the internal
( functi on) name is ignored. Thus, if DiagExtract.m is the file that defines a
function named: di agonal _ e xtracti on, you would invoke the function by
typing in the command window:
Di agExtract
80
functi on [] = pri nt_ re sul ts (x)
The variables that you pass to the function do not need to have the same
name as those in the function definition line.
% DiagExtract returns the diagonal elements of a square matrix (not single values).
This is the first line of text that appears when a user types he l p
function_name at the Matlab prompt. Further, the l ookfor searches and
displays only the H1 line of the functions. Because this line provides
important summary information about the m-file, it is important to make it
as descriptive as possible.
% This function takes as input a square matrix named X and does the followings:
% 1. If by mistake the user does not enter a square matrix, it returns
% an error message
% 2. If a square matrix is correclty entered, then it returns the
% elements of its main diagonal in vector V
When you type he l p function_name, Matlab displays the comment lines that
appear between the function definition line and the first non-comment
(executable or blank) line. The help system ignores any comment lines that
appear after this help block.
81
5.1.1.4 The Body Text
The function body contains all the Matlab code that performs computations
and assigns values to output arguments. The statements in the function
body can consist of function calls, programming constructs like flow control
and interactive input/output, calculations, assignments, comments, and
blank lines.
% This function uses the error build-in function that displays a message
% and aborts the function's execution
5.2 Scripts
On the other hand, scripts can operate on existing data in the workspace, or
they can create new data on which to operate. Although scripts do not
return output arguments, any variables that they create remain in the
workspace, to be used in subsequent computations. In addition, scripts can
produce graphical output using functions. Scripts are useful for automating a
series of steps that are needed to be performed many times (e.g. to create a
82
script that calls various options pricing function in order to price a call option
and compare the pricing accuracy of each model).
Lets say that we need to create a script with the name CompuStat.m that
should store in a vector named Data, the mean, standard deviation, median,
covariance, minimum and maximum of the main diagonal of a magic square.
Figure 13, shows how a version of such a script might look like for an 8-by-8
magic square.
83
Try to see what this script does. After executing the script, figure out what is
the difference between the command di sp and the fpri ntf. Use the command
who to view the scripts variables that are saved in the workspace. Notice
that a script does not has the same structure as a function. Moreover,
observe on Figure 13 that on the bottom of the Editor/Debugger there is a
predefined caption area that indicates that the current m-file is a script.
Important Note: when you start writing scripts and functions that are
stored in a certain directory, you occasional need to see what files are
included in this directory. To do so, from the command window you can use
the di r command (the same one as used in the MS-DOS) to view the
contents of Matlabs current directory or what to view all m-files in the
directory. Additionally, you can use cd directory_name to set the current
directory to the one specified and cd .. to move to the directory above the
current one. Moreover, de l e te file_name deletes the specified file, and pwd
prints on the screen the current directory.
84
Sixth Section
6. Cells and Structures
Structures are collections of different kinds of data organized by named
fields. Cell arrays are a special class of Matlab arrays whose elements
consist of cells that themselves contain Matlab arrays. Both structures and
cell arrays provide a hierarchical storage mechanism for dissimilar kinds of
data. They differ from each other primarily in the way they organize data.
You access data in structures using named fields, while in cell arrays data is
accessed through matrix indexing operations [2].
6.1 Cells
A cell array is a Matlab array for which the elements are cells, containers
that can hold other Matlab arrays. For example, one cell of a cell array might
contain a real matrix, another an array of text strings, and another a vector
of complex values [2]. Moreover, you can build cell arrays of any valid size or
shape, including multidimensional structure arrays. Figure 14 gives an
illustration on how a 2-by-2 cell array might look.
85
To create a cell array use the command: ce l l . For example if we want A to be
a 3-by-3 cell array, then you should use the following syntax:
A=ce l l (3,3)
to get:
A =
[] [] []
[] [] []
[] [] []
That is, the A has been created to be a 3-by-3 empty cell array. The cells
identification is the same as with matrices. The upper left cell
location/position is (1,1), the next cell in the same row is (1,2) and so on
(single value indexing is allowed also). You can fill a cell array by assigning
data to individual cells one at a time always supporting the correct cell
location/index. Matlab has two default ways to store data (scalars, vectors,
matrices, strings, cells, etc) to cells:
Cell indexing
Enclose the cell subscripts in parentheses using standard array notation.
Enclose the cell contents on the right side of the assignment statement in
curly braces, "{ }" [2]. For example:
86
A =
[3x3 double] 'Anne Smith' []
[3.0000+ 7.0000i] [1x21 double] [ 5]
{2x1 cell } [] [2x2 double]
Content indexing
Enclose the cell subscript s in curly braces using standard array notation.
Specify the cell contents on the right side of the assignment statement [2].
For example:
A{3,1} = G; A{3,3}=ones(2,2);
If you assign data to a cell that is outside the dimensions of the current
array, Matlab automatically expands the array to include the subscripts you
specify. It fills any intervening cells with empty matrices. For example, the
assignment below turns the 3-by-3 cell array A into a 3-by-4 cell array [2]
(note that the same holds for vectors and matrices with the only difference
that empty elements are assigned with zero values).
to get:
A =
[3x3 double] 'Anne Smith' [] []
[3.0000+ 7.0000i] [1x21 double] [ 5] []
{2x1 cell } [] [2x2 double] [1x27 char]
87
The only difference between the ce l l command and the cell and content
indexing is that by using ce l l you pre-allocating the cells dimensions.
You can use content indexing on the right side of an assignment to access
some or all of the data in a single cell. Specify the variable to receive the cell
contents on the left side of the assignment. Enclose the cell index expression
on the right side of the assignment in curly braces. This indicates that you
are assigning cell contents, not the cells themselves. For example, to store to
B the 3-by-3 matrix that is located in A(1,1), you should do the following:
B=ce l l {1,1};
to get:
B =
1 4 3
0 5 8
7 2 9
and to save in C the 2nd and 3rd elements of the vector that is saved in the
(1,1) cell of G which is saved in the (3,1) cell of A you do the following:
C= A{3,1}{1,1}(2:3)
to get:
C =
6 9
If you like to save in D the cells (1,2) to (2,3) of A (that is to create a 2-by-2
cell array) you do the following:
D=A(1:2,2:3)
to get:
D =
'Anne Smith' []
88
[1x21 double] [5]
So, if { } are used after a cell array then Matlab returns the arrays contents
but if ( ) are used instead, then it returns cells. To access sub-sets of
information stored in a cell use first { } to access the cell and after used ( )
to access the info you want.
Before leaving this section, notice the existence of two very useful cell arrays
functions. These are: ce l l di sp that recursively displays the contents of a cell
array, and ce l l pl ot displays the structure of a cell array as nested coloured
boxes. Further info for cell arrays can be obtained from the Matlabs online
help facilities.
6.2 Structures
Structures are Matlab arrays with named data container" called fields. The
fields of a structure can contain any kind of data. For example, one field
might contain a text string representing a name, another might contain a
scalar representing a billing amount, a third might hold a matrix of medical
test results, and so on. Like standard arrays, structures are inherently array
oriented. A single structure is a 1-by-1 structure array, just as the value 5 is
a 1-by-1 numeric array. You can build structure arrays with any valid size or
shape, including multidimensional structure arrays (see figure below) [2].
89
Building structure arrays using assignment statements
You can build a simple 1-by-1 structure array by assigning data to individual
fields. Matlab automatically builds the structure as you go along. For
example, create the 1-by-1 patient structure array shown at the beginning of
this section [2]:
patient =
name: 'John Doe'
billing: 127
test: [3x3 double]
patient =
1x2 struct array with fields:
name
billing
test
The patient structure array now has size [1 2]. Note that once a structure
array contains more than a single element, Matlab does not display
90
individual field contents when you type the array name. Instead, it shows a
summary of the kind of information the structure contains.
You can also use the fi e l dname s function to obtain this information.
fi e l dname s returns a cell array of strings containing field names (see the
online help).
As you expand the structure, Matlab fills in unspecified fields with empty
matrices so that:
ans =
name: 'Alan Johnson'
billing: []
test: []
where the arguments are field names and their corresponding values. A field
value can be a single value, represented by any Matlab data construct, or a
cell array of values. All field values in the argument list must be of the same
scale (single value or cell array). To create the structure with the patient info
shown before you should have the following syntax (the first command line
instructs for the creation of a 1-by-3 structure will all fields set to empty):
91
patient(1)=struct('name', 'John Doe', 'billing', 127.00, 'test', ...
[79 75 73; 180 178 177.5; 220 210 205]);
patient(2)=struct('name', 'Ann Lane', 'billing', 28.50, 'test', ...
[68 70 68; 118 118 119; 172 170 169]);
patient(3)=struct('name', 'Alan Johnson', 'billing', [], 'test', []);
The view an entire field this can be done with the following example syntax:
structure_name.field_name
patient.name
ans =
John Doe
ans =
Ann Lane
ans =
Alan Johnson
To view the fields data associated with a certain structure entry, the calling
syntax should be of the form:
structure_name(index_of_entry)
ans =
name: 'Ann Lane'
billing: 28.5000
test: [3x3 double]
92
structure_name(index_of_entry).field_name( )
ans =
118 118
172 170
Useful build-in functions that can make the structures handling much easier
include:
Structures and cell arrays are very useful when you need to write a program
that handles various data types. It is a challenge to work with such data
types. Before attempting writing a segment of programming code based on
these make sure that you have spent a lot of time reading the Matlabs
online help.
93
Seventh Section
7. Entering and Saving Data Files
Matlab can be used to both load a file of data from an external source and to
save to your PC data-sets that are located in the workspace or that are
created from a function. When you have to deal with small amount of data,
then you can enter them by hand either in the command window or in the
Editor/Debugger. But when you have to work with a large amount of data
retrieved by an external source (e.g. you need to process the historical daily
prices for S&P 500 from 1985 to 1999, saved in a file that was downloaded
from the Internet), then it is an imperative need to use some build-in
functions that can read files of data. Although there are different commands
that can load in workspace various types of data files, we review the two
most important ones.
The filename is better to either have the extension *.txt or *.dat because if it
does not have any extension, then the l oad has a different interpretation (see
he l p l oad for further details). If the file you want to retrieve is in a different
location than the one that the Matlabs current directory looks, then a
complete path name should accompanied this command, for example:
If the l oad command is entered properly, then the contents of the ASCII file
will be stored in a matrix with the dimensionality of the data saved in the
ASCII file. In their simplest form, ASCII files contain rows and columns of
data separated by either a tab or a space. To be accessible by l oad the file
should not contain any text or missing values and all columns and rows
94
should have the same number of elements (of course the advance user can
handle via certain methodology missing values and text in an ASCII file).
To learn on how ASCII text data look, you can use Microsoft Excel that
can handle such data. For example, enter the following data (Figure 15) in a
new Excel spreadsheet starting from cell (A1):
95
Figure 16: Excels Save As window
If a path is not provided with filename, this command saves the elements of
the variable_name in a file with the complete name filename.ext (where ext
stands for the extension of the filename and for consistency try to always use
.txt) in the current directory. If the scalar/vector/matrix (you cannot save cell
arrays or structures with this command unless first you extract their data in
a matrix or a vector variable) that is located in the workspace under the
96
name variable_name has components like: NaN or Inf, then these are saved
as text and not numbers in the saved txt file.
Concerning the options in the calling syntax, this can take the following
values for ASCII data saves (Table 13):
The use of ascii is common and satisfactory for most programming needs.
Read/save
File Format Extension File Content Returns
Command
Saved MATLAB Variables in the
mat l oad/s ave
workspace file
Text Comma-separated
csv cs vre ad/cs vwri t e Double array
numbers
dlm Delimited text dl mre ad/dl mwri t e Double array
tab Tab-separated text dl mre ad/dl mwri t e Double array
Data in Common Cell array of CDF
cdf cdfre ad
Data Format records
Flexible Image Primary or
Scientific
fits Transport System fi t s re ad extension table
Data
data data
Data in
HDF or HDF-
hdf Hierarchical Data hdfre ad
EOS data set
Format
Double or cell
Spread- xls Excel worksheet xl s re ad
array
sheet
Lotus 123 Double or cell
Wh1 wk1re ad
worksheet array
Table 14: File formats that Matlab can handle.
Use the he l p fi l e formats to see the file formats that Matlab can handle, or
use the he l p to see the calling syntax of a certain read/save command.
97
Eighth Section
8. Case Studies
In the following sub-section, some very useful examples with functions and
scripts are illustrated. Read, implement and execute the codes that are
given. Try to change the code. Experiment by adding your own command
lines. Of course, for the needs of the course, you can find all needed
functions, scripts and datasets in the folder named as:
Matlab Examples
Depending on the place you are, this folder may be in different locations.
Send me an email or ask me in class for the exact location of this folder.
c BSM = Se dT N ( d 1 ) Xe rT N ( d 2 )
where,
ln(S / X ) + ( r d + s 2 / 2 )?
d1 = ,
s T
d 2 = d1 s T ,
and,
98
1
1 x z2
N( z ) =
2p
e 2 dz
represents the cumulative normal distribution function with mean zero and
unity standard deviation (the Matlab build in function is named as:
normcdf).
The value of a European put option can also be defined via the BSM as:
p BSM = Xe rT N ( d 2 ) Se dT N ( d 1 )
To validate the formula, via the script create a table that tabulates the call
and put values against the moneyness ratio, S, and maturity, T. The data
should be loaded from a text file (that the user creates either by hand or via
99
a function) named as options_data.txt in which the columns should contain
S, X, T, s, r, d. The data values are given below:
After creating the text file, you should have a 108-by-6 table since for each
value of T and s you have nine different possible values for S.
100
8.1.2 BSM Derivatives
From the same script as above, call a function with the name: BSMde rivatives
that returns the partial derivatives of the BSM formula (known as the Greek
letters) for both the call and the put value. The partial derivatives are:
delta: c / S = N ( d 1 ) e dT , p / S = N ( d 1 ) e dT
n ( d 1 )S s rT
theta: c / T = rXe N (d2 )
2 ?
n ( d 1 ) Ss rT
p / T = + rXe N ( d 2 )
2 ?
n ( d1 ) n( d 1 )
gamma: 2c / S 2 = , 2 p / S 2 =
Ss T Ss T
vega: c / s = S T n ( d 1 ) , p / s = S T n( d 1 )
where,
1
e z / 2
2
n( z ) =
2p
represents the normal probability density function with mean zero and unity
standard deviation (the build in function is named as normpdf). The
BSMde ri vati ve s calling syntax should be :
The function should make similar checks as before. The output of the
function BSMde ri vati ve s should be a row vector if the input arguments are
single values or a two dimensional array if the input arguments are vectors
with the following format:
101
8.1.3 BSM Plots and Surfaces
Make the following plots:
Two subplot figures, one for call options with T=0.15 and s=0.20, and
one for put options with T=0.25 and s=0.20 that plot S against all
partial derivatives. Give titles and axis names.
A 3D surface of the cBSM and pBSM versus the S/X and T (note that in
order to create a smooth surface you should create a dense mesh-
grid) for the ranges:
for:
min | g ( e ) |=| c mrk c BSM ( S' , X ' ,T ' , s imp , r' , d' ) |
s imp
102
for simp. It is known that such equation has no analytic solution, so to solve
it someone has to implement a numerical root-finding algorithm. The most
well known root finding algorithm for the implied volatility problem is the
Newton-Raphson method.
The Newton method is very simple and quite fast method. It can be
summarized in three steps:
0
Step #1: give an initial guess for s imp (e.g. s imp = 0.1 )
mrk
k k 1 g( e ) k 1 c c BSM
s imp = simp = simp
g' ( e ) c BSM
S
k k 1 c mrk c BSM
s imp = s imp +
c BSM
S
for k=1,2,3,.
k
Step #3: If |g(e)|<e then stop and return s imp , otherwise go to Step
103
arguments precede the optional ones (the optional are dv, maxNumIter
and tol).
Use as inputs the initial data from the loaded txt file (without considering s).
The function should make similar checking like previous functions with the
additional that:
If not specified, maxNumIter should be equal to 100.
If not specified, tol should be 1e-5.
At the beginning of the function, it should be tested whether with a
small value of s (e.g. s=0.001) the cBSM and pBSM are greater than cmrk
and pmrk respectively; if such condition holds (it can be observed in
practice as an arbitrage result), an implied volatility value that
minimizes |g(e)| does not exist, so the function should return a
NaN value.
To help the algorithm convergence rate and to save computing time,
the starting values for the algorithm should be given from the
following approximation suggested by Bharadia, Christofides and
Salkin [3]:
2p c mrk d
0
for call options: s imp = , and,
? Xe rT + d
2p p mrk + d
0
for put options: s imp =
? Xe rT + d
with,
d = 0.5( S Xe rT )
104
the ones that you have initially used (these are the random values) to
price calls and puts with the BSM. Note that the implied volatility of
calls and puts for should match for similar input arguments. Plot the
difference to visualize that always the dollar difference is less than
tol (given that the algorithm iterations were adequate to secure
convergence).
x k +1 = x k af ' ( x k )
for k=1,2,3,.
f ' ( x k ) is a row vector that includes the first order partial derivatives of
f(.) w.r.t xs at the kt h iteration. The parameter a is a positive scale
function that lies between 0 and 1 and is a learning rate that sets the
step size. Large values of a force the algorithm to oscillate around the
minimum point or even diverge, whereas small values of a lead to more
105
stable convergence but with extremely slow rate. Typical values of a
range between 0.01 and 0.15 depending on the faced problem.
f ( x ) f ( x ) f ( x )
f ' ( x) = L
x 1 x 2 x n
Step #3: Increase: k k+1 and if the current iteration index k is larger
than the maximum number of iterations or if af ' ( x k ) <e then stop and
f ' ( x k ) is a row vector that includes the first order partial derivatives of
f(.) w.r.t xs at the kt h iteration and [ f ' ' ( x k )] 1 is a square matrix that
represents the inverse of the second order partial derivatives of f(.) w.r.t
xs (Hessian matrix) at the kt h iteration.
106
Specifically, f ' ' ( x ) for a function with n variables is:
2 f ( x) 2 f ( x) 2 f ( x )
K
x 12 x 1 x 2 x 1 x n
2
f ( x) 2 f ( x)
K
2 f ( x )
f ' ' ( x ) = x 2 x 1 x 22 x 2 x n
M M M M
2 f ( x) f ( x)
2
f ( x)
2
x n x 1 x n x 2 x n2
f ' ( x k )[ f ' ' ( x k )] 1 <e then stop and return x k + 1 , otherwise go to Step
#2 and perform one more iteration of the algorithm (the e is the desire
accuracy, usually set to a small quantity such as 1e-6, whereas the
maximum number of iterations depends solely by the experience of the
researcher).
Both the gradient descent and the Newton descent algorithms have inherent
problems with their implementation. For example, the user should
magically define the correct value of the learning parameter a in order to
succeed a robust convergence of the algorithm when it comes to implement
the gradient descent algorithm, or concerning the Newton descent one, when
the Hessian matrix is singular and its inverse does not exist then it is not
applicable. Moreover, there is no way to secure that the initial point to set
up the algorithm will eventually help in reaching the minimum point. Most
of the times and when the user does not have a detail overview of the faced
problem, the initial value of x might be too far from the minimum point,
preventing in this way the algorithm to converge.
There are many suggestions to suppress these problems (i.e [4], [5]). In here,
we will implement these two algorithms just for getting the feeling on the
way that a minimization algorithm can be used. The user can later improve
the functions that will be illustrated according to his/her needs.
107
To implement the previous algorithms, the user should be in a position to
find the gradient vector and the Hessian matrix. Although it is better to work
with the exact first and second order partial derivatives of the function via
their functional form, a more flexible, practical and quite accurate way is to
create two functions in Matlab that calculate these with two sided finite
differencing methods. That is, instead of evaluating a function at a point x
by using the functional form of the gradient vector and the Hessian matrix,
it is easier to find these information via numerical differentiation (two sided
finite differencing).
The centred and evenly spaced finite difference approximation of the first
order partial derivatives (gradient vector) of a function f at point x is (for
simplicity assume a two variable function with x1 and x2 to be the unknown
variable the extension to the n dimensional case is trivial):
f ( x ) f ( x1 + h, x 2 ) f ( x1 h, x 2 )
x 1 2h
f ( x ) f ( x1 ,x 2 + h ) f ( x1 , x2 h )
x 2 2h
h = max(| x |,1) 3
The centred and evenly spaced finite difference approximation of the second
order partial derivatives (Hessian matrix) of a function f at point x is (for
simplicity assume a two variable function with x1 and x2 to be the unknown
variable the extension to the n dimensional case is trivial):
f 2 ( x ) f ( x 1 + 2h , x 2 ) + f ( x 1 2h , x 2 ) f ( x 1 2h , x 2 ) f ( x 1 + 2h , x 2 )
x 12 4h 2
108
f 2 ( x ) f ( x1 + h ,x 2 + h ) + f ( x1 h ,x 2 h ) f ( x1 h , x2 + h ) f ( x1 + h , x2 h )
x 1 x 2 4h 2
f 2 ( x ) f 2 ( x )
x 1 x 2 x 2 x 1
f 2 ( x ) f ( x 1x 2 + 2h ) + f ( x 1 x 2 2h ) f ( x 1 x 2 2h ) f ( x 1 x 2 + 2h )
x 22 4h 2
h = max(| x |,1) 4
Having in mind the above, write a script with the name: FunctionMin.m that
will do the following:
Make the 3D surface and the contour plots of the function:
f ( x 1 , x 2 ) = e x ( 4 x 2 + 2y 2 + 4 xy + 2y + 1)
fe val (@funToMin,x)
where x is a two element row vector (or m-by-2 array) with x(1) and
x(2) to represent x1 and x2 respectively.
Do a new figure that creates the contour plot of this function, with
the value of the contours to range between 0 and 80 (for example use:
V=[0:0.25:2, 3:1:10, 20:10:80]).
109
Call a function with the name: GradDe sce nt that implements the
gradient descent algorithm for minimizing the aforementioned
function. The calling syntax of this function should be:
This function should call another function with the name: NumerDers
and with the following calling syntax:
After you have called the function, plot on the contour figure the
algorithms trajectory to the minimum found in xVals. Call once
more the function with x0=[-1 -2] and add the new trajectory to the
contour figure. Use lr=0.25 and maxIterNum=200. Use gte xt to
enter a text that indicates the trajectory.
110
Call a function with the name: Ne wton that implements the Newton
descent algorithm for minimizing the aforementioned function. The
calling syntax of this function should be:
HessVals = NumerHessian(fun,x)
After you have called the function, create a new contour figure of the
function and plot on it the algorithms trajectory to the minimum
found in xVals. Call once more the function with x0=[-1 -2] and add
the new trajectory to the contour figure. Use gte xt to enter a text that
indicates the trajectory.
111
8.3 Portfolio Optimization
Many times, a researcher needs to create a portfolio of securities that for a
desire level of return/profit, it bears the least/minimum risk. The portfolio
optimization problem has been defined since Markowitz (1952) who assumed
that the risk associated with a portfolio can be measured with variance.
E( r p ) = W T e
where rp is the weighted average return of the portfolio and E(.) is the
expectation operation. The weight representation of each asset in the
portfolio is given by W and the expected return of each asset is given by e as
follows:
w1 r 1
w r
W = 2 and e = E
2
M M
wn rn
s P2 = W T OW
112
s 11 s 12 L s 1n
s s 22 L s 2n
O = 21
M M M M
s n 1 s n 2 L s nn
is required that the sum of the assets weights should be added to one:
W TNI = 1
From the above it is obvious that the portfolio optimization problem can be
solved via the minimization of a quadratic volatility function subjected to
linear constrains, one related with the portfolio expected return and another
that assures that all available funds are invested. There are several
convenient mathematical methods for solving this problem. In here, in first
place, it is illustrated the one that is called the method of the Langrangean
multiplier that allows the solution of the general portfolio problem with short
sales with the requirement that the constraints must be in equality form.
When you take the PBA 521: Financial Theory course, you will have to solve
such kind of problems.
The example shown below is copied from the class notes of the above course
offered in 2001 by Professor Spiros Martzoukos. It is the case of three risky
assets without a risk-free rate (it is trivial to generalize it to n risky assets).
The inclusion of the risk free rate is easy; by treating the risk-free rate as a
risky asset with zero volatility and zero covariance with all the other assets.
The problem formulation that achieves an expected return equal to R
follows:
min W T O W
wi
s.t.
113
WTe = R
W TNI = 1
min w 2A s A
2 2 2
+ wB s B + wC2 s C2 + 2w A w B s AB + 2w A wC s AC + 2w B wC s BC
wi
s.t.
w A E ( r A ) + w B E ( r B ) + wC E( r C ) = R
w A + w B + wC = 1
Note: If we do not use the first constraint and in the absence of a risk-free
rate we will get the minimum variance portfolio. It is actually advisable to
first get the minimum variance portfolio before we proceed in a real problem.
Then, by changing the level of desire return, we trace points on the efficient
frontier.
w A E ( r A ) + w B E ( r B ) + wC E( r C ) = R
to
R w A E ( r A ) + w B E( r B ) + wC E ( r C ) = 0
?( R w A E ( r A ) + w B E ( r B ) + wC E ( r C )) = 0
114
Since this equals zero, we add it to the objective function that we want to
minimize without affecting the results. Finally, we minimize the quadratic
function without any constraints. Thus, we have to minimize a function, f (so
it can also be solved with methods that we have seen before). So, after
substitution we have:
f = wA s A + wB
2 2
s B + ( 1 w A + w B ) 2 s C2 + 2w A w B s AB + 2w A ( 1 w A + w B ) s AC
2 2
+ 2w B ( 1 w A + w B ) s BC + ?( R w A E ( r A ) w B E ( r B ) ( 1 w A + w B ) E ( rC ))
We need to solve this problem to find the weights of the three assets in the
portfolio. We thus first find the solution to w A , w B and ?. The way to solve
the above problem is now easy. We take the partial derivatives each time in
respect to one of the three unknowns and set them equal to zero, and we will
derive a set of three equations with three unknowns. The first is the partial
derivative of f w.r.t w A , the second w.r.t w B and the third w.r.t the
Langrangean multiplier ?.
2
2 w As A + ( 2w A + 2w B 2 ) s C2 + 2wB s AB + ( 2 4w A 2wB ) s AC 2w B s BC
?E ( r A ) + ?E( rC ) = 0
2
2 wB s B + ( 2w A + 2w B 2) s C2 + 2w A s AB 2w A s AC + ( 2 2w A 4wB ) s BC
?E ( r B ) + ?E ( rC ) = 0
R w A E ( r A ) wB E ( r B ) ( 1 w A w B ) E( rC ) = 0
115
r A 0.05
e = E rB = 0.10
rC 0.15
Write a script with the name: MeanVarMin.m that will do the following:
Saves in a column vector the weights for the solution of the above
mean-variance minimization problem given by:
Create an m-file with the analytic expression of the function f with the
name: portFun.m with the following syntax:
f=portFun(x,r,V,R)
116
change slightly the Ne wton function so that its calling syntax
becomes:
[MinPoints] = Ne wtonPort(fun, x, r, V, R)
Add a risk free asset with expected return 1%, find and plot the
efficient frontier. Create a new m-file with the name:
portFunRiskFree.m that includes the new expression of f after the
inclusion of risk-free rate (hint: find which components are zero-
valued and ignore them). Create a third figure that combines the two
previous ones. If you are familiar with investment theory, you can
view various interesting components (e.g. two fund separation
theorem, capital market line, etc).
117
References
[1] Ela Pekalska, Marjolein van der Glas, (2001), Introduction to MATLAB,
Pattern Recognition Group, Faculty of Applied Sciences, Delft University
Technology.
[4] Miranda M. and Fackler P., (2002), Applied Computational Economics and
Finance, Massachusetts Institute of Technology.
[9] Ferrari S., (2000), Tutorials in Robotics and Intelligent Systems: Part IV.
Introduction to MATLAB Optimization Toolbox, Department of Mechanical
and Aerospace Engineering, Princeton Unive rsity.
118