Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming...

40
Introduction to Matlab Programming Ludovic Cal` es * November 8, 2012 Abstract This course is designed to make the students autonomous in the implementation of their financial and economical models by providing some software engineering skills especially in Matlab. The class is divided in two sections of seven courses. The first section is dedicated to Matlab. It is itself divided in two parts: one introducing the basics of Matlab programming, the next one dealing with Matlab toolboxes. The second section focuses on software engineering concepts and applications. The following lecture notes are the first part of the first section, introducing Matlab basics. 1 Introduction 1.1 What is Matlab ? Matlab stands for MATrix LABoratory. It is a numerical computing application proposing both a programming language and its development environment. It is developed since 1984 by Mathworks. It is composed of a basic set of functions which can be extended by toolboxes (additional sets of functions). Typically, a toolbox is dedicated to a specific field of application such as finance, biology, mechanics, etc. As the language is based on matrix manipulation, it is particularly used for linear algebra and numerical analysis. 1.2 Free Alternatives to Matlab : Scilab & Octave Scilab is a free alternative to Matlab. It has been developed since 1990 by French researchers from INRIA and ENPC and it is now managed by Digiteo Fondation. It is mostly compatible with Mat- lab, i.e. your Matlab programs are likely to run with Scilab. It is available in French, English, Italian & German under Linux, Mac OS and Windows. It can be found at www.scilab.org. Octave is another free alternative to Matlab which mostly compatible with it. It is available under Linux, Mac OS and Windows. It can be found at www.gnu.org/software/octave. 2 Getting Started Matlab is a language based on matrix manipulation. In the following, we study the basics of the Matlab syntax. * I am very grateful to Peiman Asadi for his numerous comments which greatly helped to improve these lecture notes. 1

Transcript of Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming...

Page 1: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Introduction to Matlab Programming

Ludovic Cales∗

November 8, 2012

Abstract

This course is designed to make the students autonomous in the implementation of theirfinancial and economical models by providing some software engineering skills especially inMatlab. The class is divided in two sections of seven courses. The first section is dedicated toMatlab. It is itself divided in two parts: one introducing the basics of Matlab programming,the next one dealing with Matlab toolboxes. The second section focuses on software engineeringconcepts and applications. The following lecture notes are the first part of the first section,introducing Matlab basics.

1 Introduction

1.1 What is Matlab ?

Matlab stands for MATrix LABoratory. It is a numerical computing application proposing both aprogramming language and its development environment. It is developed since 1984 by Mathworks.It is composed of a basic set of functions which can be extended by toolboxes (additional sets offunctions). Typically, a toolbox is dedicated to a specific field of application such as finance, biology,mechanics, etc. As the language is based on matrix manipulation, it is particularly used for linearalgebra and numerical analysis.

1.2 Free Alternatives to Matlab : Scilab & Octave

Scilab is a free alternative to Matlab. It has been developed since 1990 by French researchers fromINRIA and ENPC and it is now managed by Digiteo Fondation. It is mostly compatible with Mat-lab, i.e. your Matlab programs are likely to run with Scilab. It is available in French, English,Italian & German under Linux, Mac OS and Windows. It can be found at www.scilab.org.

Octave is another free alternative to Matlab which mostly compatible with it. It is available underLinux, Mac OS and Windows. It can be found at www.gnu.org/software/octave.

2 Getting Started

Matlab is a language based on matrix manipulation. In the following, we study the basics of theMatlab syntax.

∗I am very grateful to Peiman Asadi for his numerous comments which greatly helped to improve these lecturenotes.

1

Page 2: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

2.1 Light on

By clicking on the Matlab icon, you launch the Matlab environment. It is divided in several areasamong which:

• the command window. It is the window where you will enter your commands, launch yourprograms, visualize the results, etc. It is waiting for a command when the prompt >> isdisplayed.

• the current folder window lists the files it contains.

• the work space window displays the variables in use and their contents.

• the command history window displays the last commands entered.

You can choose which windows to display by clicking on ”Window” in the menu bar and selectingsome windows. Then, save your desired layout by clicking on ”Save Layout”.

2.2 Folder Structure

As seen before, you can explore the folder structure using the current folder window (folder=directory).An alternative is to use the command ’cd’ in the command window to change the current workingfolder. However, you need to provide the command with a path, i.e. a sequence of folders delimitedby ’/’ representing a certain folder. This path can be absolute or relative. An absolute path is acomplete sequence of folders starting from the root. For instance, in Example 1, we change theworking folder to the directory MyMatlabPrograms in the root of hard drive C: by calling the ’cd’command followed by the absolute path C : \MyMatlabPrograms. In opposition to the absolutepath, a relative path is a sequence of folders starting from the current folder. In this second case, use’..’ to change the current folder to the one above it, and the name of folders to move up into thesefolders. For instance, in Example 2, considering that the current folder is C : /Windows/System32,we move down two folders from this folder and move up into the folder MyMatlabPrograms.

Example 1.

>>cd C:/MyMatlabPrograms

>>

Example 2.

>>cd ../../MyMatlabPrograms

>>

Remark that using ’cd’ alone provides the current directory.

Example 3.

>>cdC:/Windows/System32

You can create a new folder in the current working folder with the ’mkdir’ command and delete afolder with the ’rmdir’ command. The following example creates the folder ’TestFolder’ and deleteit immediately after.

2

Page 3: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 4.

>> mkdir TestFolder

>> rmdir TestFolder

To obtain the list of files in the current working folder, use the ’ls’ command.

2.3 Basic Data Types

In Matlab, there are five main data types: boolean, char, numeric, cell and structure. In this sec-tion, we introduce the three first types as they are the simplest and most important ones. Cells andstructures are presented in Section 4.

2.3.1 Declaration & Assignment

First, let introduce the declaration and assignment of a variable. The declaration is easy because –unlike many other programming languages – Matlab does not require to declare the variables beforeusing them. In other words, you can directly assign a value to a variable to create this variable. Theassignment of a value to a variable is performed using the operator ’=’, i.e.

A = 1

gives the value 1 to the variable A. Check in the work space that the variable has been createdand assigned the value 1. Remark that ending a line with a semi-colon ’;’ does not display the resultin the command window (see Example 6) whereas omitting it would display the result (see Example5).

Example 5.

>> A = 1;

>>

Example 6.

>> A = 1

A =

1

Note that Matlab is case sensitive, i.e. it differentiates commands using uppercase and lowercaseletters. For instance, we can have two variables named a and A with a 6= A. In addition, you mustgive your variables names that are not already used by Matlab (for instance, pi is already used byMatlab).

2.3.2 logical/boolean

Boolean values are 0 and 1, false and true respectively. This data type is mainly used in conditionalstatements as we see in Section 2.7.

3

Page 4: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

2.3.3 char

char stands for character. An array of characters is called a string (see Section 2.5).

Example 7.

>> myCharacter = ’a’;

Remark that the character has to be placed between quotation marks.

2.3.4 numeric

The data type numeric includes integers and reals. The double data type is the default data type inMatlab. The integer data type is not widely used except for indexing matrices as presented in thenext section. double are double precision numbers meaning that their value is coded over 64 bits,i.e. their precision is 253.

2.4 Matrices

Let recall that a matrix is an array of numbers. It is easily implemented by entering its values insquare brackets [ ], delimiting them with spaces and using the semi-colon ′;′ to change row in thematrix.

Example 8.

>> A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]

A =

1 2 3

4 5 6

7 8 9

Then, you can access the element (2, 3) by typing A(2, 3)

Example 9.

>> A(2,3)

ans =

6

Remark that the indices of the matrix have to be integers. A common error is Index exceeds matrixdimension. It means that you tried to access an element out of the matrix boundaries.

Example 10.

>> A(4,3)

??? Index exceeds matrix dimension.

An easy way to create a n1 × n2 matrix and assign it with zeros is to use the function zeros(n1, n2)where n1 is the number of rows and n2 the number of columns. The same function exists with ones,ones(n1, n2). In order to create an identity matrix, use eye(n).

4

Page 5: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 11.

>> A = zeros(3,4)

A =

0 0 0 0

0 0 0 0

0 0 0 0

You can transpose a matrix using the apostrophe ”′”. For instance,

Example 12.

>> A = [1 2 3];>> B = A′

B =123

2.5 Strings

As a matrix is an array of numbers, a string is an array of characters. A string must be writtenbetween apostrophes, e.g. example 13. An apostrophe in a string is indicated by two apostrophesas showed in example 14.

Example 13.

>> myString = ’Hello world’;

Example 14.

>> myString = ’David’’s book’

myString =

David’s book

As with matrices, you access a specific character by its index. For instance, the 5th character ofmyString is ′o′.

Example 15.

>> myString = ’Hello world’;

>> myString(5)

ans =

o

2.6 Operators

Let remember that an operator is the symbolic representation of a mathematical operation.

5

Page 6: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

2.6.1 Boolean Operators

The boolean operators relate two variables and return a boolean. For instance, consider two booleanvariables A and B. The logical operators and and or are defined as follow

A B A and B0 0 00 1 01 0 01 1 1

A B A or B0 0 00 1 11 0 11 1 1

The logical operator in Matlab are:

== is equal to∼= not equal to< is less than<= is less than or equal to> is greater than>= is greater than or equal to& logical and‖ logical or∼ logical not

Example 16.

>> A = [ 1 1 ];

>> A & [ 1 0 ]

ans =

1 0

Remark that if your variables are not boolean then any non-zero value is considered to be true.Zero continues to be false.

2.6.2 Arithmetic Operators

The arithmetic operators in Matlab are:

+ plus− minus∗ multiplication/ divisionˆ power.∗ element-wise multiplication./ element-wise division. element-wise power

Example 17.

>> a = 1.2;>> b = 5 ∗ a^2 + ab =

8.4000

6

Page 7: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 18.

>> A = [1 2 3];>> B = [4 5 6];>> A ∗B′ans =

32

Example 19.

>> A = [1 2 3];>> B = [4 5 6];>> A. ∗Bans =

[4 10 18]

2.6.3 Colon Operators

The colon is a very useful operator in Matlab. It is first used to create regularly spaced vectors. Tocreate a vector ranging from a to b with an increment i, use the following syntax:

a : i : b

For instance, the vector of the odd numbers from 3 to 11 can be written 3 : 2 : 11

Example 20.

>> A = 3 : 2 : 11A =

3 5 7 9 11

If the increment is not set by the user, its default value is 1. For instance, in the next example,3 : 11 leads to the vector ranging from 3 to 11 with an increment 1.

Example 21.

>> A = 3 : 11A =

3 4 5 6 7 8 9 10 11

The colon is also useful in order to select contiguous rows/columns within a matrix. For instance,consider a matrix A

A(:, i) selects the ith column of A.A(i, :) selects the ith row of A.A(i : j, :) selects from the ith to the jth rows of A.To delete the ith row of matrix A, use A(i, :) = []. To delete its jth column, use A(:, j) = []. As anillustration, the following example delete the second row of a matrix.

7

Page 8: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 22.

>> A = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]

>> A(2,:) = []

A =1 2 3

7 8 9

2.7 Cleaning the memory and the screen

To clean the command window, use the command clc.

To clean the memory (i.e. the workspace), use the command clear. You can delete specific variableswith clear VarName1 VarName2, where VarName1 and VarName2 are the names of two variablesthat you want deleted. Remark that calling clear all deletes not only all the variables but also thebreakpoints (introduced in Section 6.2).

2.8 Scripts

Until now, we have been typing the commands in the command window. In order to implementlonger commands – over several lines – we write them sequentially in a file. Let open a new fileby clicking on the ”New M-File”’ icon in the top left of the environment. It opens a file whoseextension is ”.m”, standing for Matlab file, in the Matlab editor window. There you can enteryour sequence of commands and save it. To run it, you have to be in this file directory and eithertype its name in the command window or click on the ”Debug/Run” icon in the editor (or press F5).

2.9 Control Flows

A control flow sets the order in which some instructions are executed. It corresponds to conditionalexpressions (if), loops (for) and conditional loops (while).

2.9.1 if

Conditional expressions are executed depending on a specific boolean condition. It has the followinggeneral form:

if( boolean condition 1 is true )follow instruction 1

elseif( boolean condition 2 is true )follow instruction 2

elsefollow instruction 3

end

Remark that the number of conditions can vary. Here, there are two conditions for illustrationpurposes only. As an illustration, in the following example, c is assign the value 0 because the firsttwo conditions are false.

8

Page 9: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 23.

a = 4;

b = 4;

if(a<b)

c = -1;

elseif(a>b)

c = 1;

else

c = 0;

end

Remark that the if/elseif/else/end commands require no semi-colon as they do not display any-thing.

2.9.2 for

For loops are iteratively repeating some instructions for different values of an iterator. In thefollowing example, the iterator is i and takes sequentially the values 1 to 10 (remark the use of thecolon to browse the values of i). This example computes (inefficiently) b = 210.

Example 24.

a = 2;

b = 1;

for i=1:10

b = b*a;

end

In this example, the sequence of operations is as follows:

1st loop i = 1 ⇒ b = 1× 2 = 22nd loop i = 2 ⇒ b = 2× 2 = 43rd loop i = 3 ⇒ b = 4× 2 = 8etc.

2.9.3 while

While loops execute repeatedly some instructions based on a boolean condition. It often requiresan iterator, here i, as in the for loop. It has the following general form:

i = 1;while( i < 10 )

follow instructionsi = i+ 1

end

Remark that the iterator i has to be incremented inside the loop, unlike for loops. Otherwise, theloop would never end. In Matlab, its syntax is as shown in the following example which computes(inefficiently again) b = 210.

9

Page 10: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 25.

a = 2;

b = 1;

i = 1;

while (i<=10)

b = b*a;

i = i + 1;

end

2.10 Read/Save Data

In order to save your data, Matlab proposes the save command which – by default – save your wholeworkspace in the ”matlab.mat” file. You can also choose to save specific data in a file – let say data1and data2 in filename – by calling the function save(’filename’, ’data1’, ’data2’).

In order to read some data from a ”.mat” file, you can call the load function as load(’filename’),where filename is the name of the ”.mat” file. To perform this, you need to be in the same folderthan the ”.mat” file. Then, the loaded data appears in the workspace along the rest of the data.

You can also read data from Excel file using the xlsread function. Its syntax is xlsread(’filename’,’sheet’)where filename is the name of the excel file and sheet is the sheet’s name to read.

In the same way, you can write in an excel file using xlswrite. Its syntax is xlswrite(’filename’, M,’sheet’,’range’) where filename and sheet are as before, M is the matrix to write in the excel fileand ’range’ specifies the cells to write in. For instance, the following example writes a 2× 3 matrixof ones in the cells B3, B4, C3, C4, D3 & D4 in the sheet ”MySheet1” of the ”MyXLSFile.xls” file.

Example 26.

M = ones(2,3);

xlswrite(’MyXLSFile’, M, ’MySheet1’, ’B3:D4’);

Remark that xlswrite(′MyXLSFile′,M,′MySheet1′); would write the matrix M in the cells start-ing from A1 (here in A1 : C2).

2.11 Display Data

To display a string or an array, use the ’disp’ command. For instance, the following example displaythe string ’Hello World’.

Example 27.

>> disp(’Hello World’);

However, before to use ’disp’ you need to have the complete string to display. Now suppose thatyou want to display the result ’myResult’ of an experiment. Then, you need to include this vari-able in your string to display. To do so, you create a string using ’sprintf ’ and display it using ’disp’.

10

Page 11: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

The function ’sprintf ’ incorporates data into a string. Its syntax is as follows:

myString = sprintf(format, myInput)

where myInput is your input data, and format is a string formating the appearance of theoutput. The string format includes format codes which convert your data and insert it into thestring. These format codes are placed in the string where you want your data to appear. This isillustrated in Example 28. The most common format codes are

%s to insert a string%d to insert an integer%X.Yf to insert a double with X number before the comma and Y numbers after.

For instance, consider the string currentStock = ’IBM’ and the double currentStockPrice = 181.705.To display the stock’s name and its price nicely, first you build the string MySentence as follows andthen display it using ’disp’.

Example 28.

>> currentStock = ’IBM’;

>> currentStockPrice = 181.705;

>> MySentence = sprintf(’The stock %s is priced %4.2f dollar.’, currentStock, currentStockPrice);

>> disp(MySentence);

The stock IBM is priced 181.71 dollar.

Remark that the price has be truncated because we ask for a precision of two digits by using %4.2f .

2.12 Getting Help

In case of trouble with a command/function’s syntax or if you are looking for something specific,you can open the help window by typing ’help’ in the command window or clicking on the help icon.An alternative is to type ’help’ followed by the command name in the command window.

2.13 Exercises

Exercise 1.

Compute the sum of integers ranging from 1 to 100.

Exercise 2.

We know that the roots of ax2 + bx+ c = 0 are

x1 = −b+√b2−4ac2a

x2 = −b−√b2−4ac2a

What are the solutions if a = 1, b = 2, c = −3 ?if a = 1, b = 4, c = −21 ?if a = 9, b = 6, c = 1 ?

11

Page 12: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Exercise 3.

Riemann sums approximate the integral∫ b

af(x)dx by

Sn =b− an

n∑k=1

f

(a+ k

b− an

)for large n.

Numerically valuate the integral∫ 2

0

√1 + ex using Riemann sums.

Exercise 4.

Simpson’s rule approximates the integral∫ b

af(x)dx by

Sn =b− a

6

(f(a) + 4f

(a+ b

2

)+ f(b)

)Again, numerically valuate the integral

∫ 2

0

√1 + ex using Simpson’s rule.

Exercise 5.

Here are the monthly returns of an hedge fund:

Jan. Feb. Mar. Apr. May June July Aug. Sep. Oct. Nov. Dec.2009 4.15% 2.98% 8.53% 4.19% 4.47% 1.16% −2.87% −0.11% −1.27% −0.69% 2.67% −0.67%2010 −1.69% −0.23% 0.52% 2.23% −1.86% 1.95% 1.23% 4.97% 0.36% 0.60% −2.51% −3.16%

Compute its average return, the standard deviation of its returns and its Sharpe ratio (SR =E[R−Rf ]√var(R−Rf )

). Consider a risk-free rate of 3% annually, i.e. Rf ≈ 0.25%. Hint: use the functions

mean(.) (providing the mean of an input vector) and std(.) (providing the standard deviation of aninput vector).

Exercise 6.

Write a program that approximates π by computing the sum π ≈ 4∑n

k=0(−1)k2k+1 . What is the

error using 100/1000/10000 terms ? (Hint: compare your result with the Matlab variable pi whichprovides the real value of π.)

Exercise 7.

Write a program solving the linear system Ax = y where

A =

3 2 −12 −2 4−1 0.5 −1

, Y =

1−20

Hint: use the functions inv(.) which provide the inverse of a matrix.

12

Page 13: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

3 Functions

A function is a sequence of instruction that performs a specific task. Unlike scripts, it is part ofa larger programs and takes both input and output arguments. It can be called by a program oranother function to perform the required task. The main advantages of using functions are to reducethe development costs (a function is written once but can be called several times) and maintenancecosts (a bug has to be corrected once and the readability of the program is increased).

A function is called by providing it with the expected input and the variable for its output:

[Output1, . . . , Outputn] = FunctionName(Input1, . . . , Inputm)

where Input1,...,m are the input variables, Output1,...,n are the output variables returned by thefunction and FunctionName is the name of the function. The name of the function has to beuniquely identified in order to avoid any ambiguity.

3.1 Mathematical Functions

In Matlab, many usual mathematical functions are already implemented. Among the most importantones, we have:

• the function sum(.) computes the sum of matrix elements by column. In the same way, prod(.)computes the product of matrix elements by column.

• the function max(.) returns the maximum of each column of a matrix. In the same way, min(.)returns the minimum of each column of a matrix.

• the function length(.) returns the number of elements in a vector. size(.) returns both thenumber of rows and columns of a matrix.

• all the usual trigonometric functions are present: sin(.), cos(.), tan(.), etc.

• all the usual exponential functions are present: exp(.), log(.) (natural logarithm), sqrt(.) squareroot, etc.

• and many others . . .

3.2 Create Your Own Functions

In the case you need a customized function, you can easily create one by following this procedure:

1. open the Matlab editor ( File/New/Function in the top left of the environment)

2. declare your function as follows

function [Output1, . . . , Outputn] = FunctionName(Input1, . . . , Inputn)

3. type down your sequence of instructions

4. save it as a ”.m” file whose name is the function’s name (FunctionName)

For instance, here is a function returning the maximum of two numbers given in input.

13

Page 14: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 29.

function TheMax = MyMaxFunction( Number1, Number2)

if( Number1 > Number2 )

TheMax = Number1

else

TheMax = Number2

end

end

3.3 Local/Gobal Variables

A local variable is a variable which is defined in a function only. Indeed, this variable is not in the(base) workspace but in a specific workspace dedicated to the function. As a consequence, thesevariables cannot be used in other functions. Here is an example of function with a local variable:

Example 30.

function TheMax = MyMaxFunction( Number1, Number2)

tmp = -inf;

if( Number1 > Number2 )

tmp = Number1

else

tmp = Number2

end

TheMax = tmp;

end

In this example, tmp is a local variable. It is created in the function and is not an output. It isdeleted from the computer’s memory at the end of the function execution and it is not visible outsidethis function.

On the other side, a global variable is a variable that is visible in some specified parts of a programand not restricted to a function only. It is important to note that a global variable has to be declaredas global in the functions where it is used. In the following example, we first declare a global variablenumber2 in the workspace, then we assign it a value and finally we call a function where number2is also global and thus is shared by both the worspace and the function. As a consequence, there isno need to provide number2 as input of the function.

Example 31.

Consider the following function:

14

Page 15: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

function [ TheMax ] = MyMaxFunction(Number1)

global Number2;

if( Number1 > Number2 )

TheMax = Number1;

else

TheMax = Number2;

end

end

Then, declare the variable Number2 as global:>> global Number2;

Next, give it a value:>> Number2 = 0;

Then, call the previous function:>> MyMaxFunction3(3)

ans =

3

>> MyMaxFunction3(-1)

ans =

0

For clarity and maintainability, minimize the use of global variables.

3.4 Inline Functions

Inline functions are short functions which require simple implementation. Their implementation isdone using the inline function whose syntax is as follows:

FunctionName = inline(expr, input)

where FunctionName is the name of the inline function, expr is a string corresponding the im-plementation and input is the input variable.

For instance, the following example creates an inline function of MyInlineFunction = 3sin(2x2).

Example 32.

MyInlineFunction = inline(′3 ∗ sin(2 ∗ x^2)′,′ x′);

Then, it is called as any function:

Example 33.

>> MyInlineFunction(90)ans =

2.7888

15

Page 16: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

3.5 Exercises

Exercise 8.

Write a function taking three variables as input and returning the minimum of them.

Exercise 9.

Write a script calling a function multiplying a number A by a factor K which is defined in thescript but which is not an input argument of the function.

Exercise 10.

Remember that the normal probability distribution function is

f(x) =1√

2πσ2e−

(x−µ)2

2σ2

Write an inline function for the normal probability distribution function with mean 1 and standarddeviation 3.

Exercise 11.

Write a function for the normal probability distribution function whose mean µ and standarddeviation σ are defined as global variables in a script calling this function.

Exercise 12.

Write a function computing the factorial of its input argument n, n ≥ 0.

Compare your results with those of Matlab built-in function factorial(.).

Exercise 13.

Write a function approximating the cosine of a number x using the following relation:

cos(x) ≈n∑

k=0

(−1)kx2k

(2k)!

Consider n = 1000.What is the error for x = 2π ?

16

Page 17: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

4 Organizing Your Data with Advanced Data Types

4.1 cell array

The cell data type is a generic type able to enclose any kind of data types. It can be a numeric,a character, etc. It is used as array of mixed types which are enclosed in curly braces { }. It isopposed to a matrix which is an array of numeric and to a string which is an array of characters. Inthe following example, we build a cell array containing a number, a matrix and a string.

Example 34.

>> A = {10 ones(4, 3) ′HelloWorld′}A =

10 [4× 3double] ’Hello World’

The elements of the cell array are accessed in the same way as matrix elements but using the curlybraces instead of the parenthesis. For instance, you can access the elements of the cell array definedin the previous example as follows:

Example 35.

>> A{2}ans =

1 1 1

1 1 1

1 1 1

>> A(3)ans =

’Hello World’

4.2 Structure

A structure is an array with different fields for each element. These fields can be of any data type andthus, as cell arrays, a structure allows to mix different data types. As an illustration, the followingexample presents a structure designed for cars. Each element of the structure represents a car andits fields correspond to the brand, model and oil consumption of the car.

Example 36.

>> Car(1).brand = ’BMW’;

>> Car(1).model = ’320 Touring 2.0’;

>> Car(1).consumption = 8.1;

>> Car(2).brand = ’Renault’;

>> Car(2).model = ’Clio III 1.2’;

>> Car(2).consumption = 7.6;

>> Car(3).brand = ’Citroen’;

>> Car(3).model = ’Berlingo 1.6 HDI’;

>> Car(3).consumption = 6.1;

This structure ’Car’ has three elements, i.e. three cars, which are characterized by three fields:brand, model and consumption. The structure elements are managed like matrix elements. Access-ing to the data of the fields is done simply as follows:

17

Page 18: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 37.

>> Car(2).model

ans =

’Clio III 1.2’

In the same way as matrices, use [ ] to delete an element of the structure. Remark that, whenhandling a structure, omitting the semicolon leads to a description of the structure (number ofelements and fields). Indeed, it would be no use to have each element displayed in the commandwindow because structures tend to be large. The following illustration shows the removal of astructure element and the display of its description.

Example 38.

>> Car(2) = []

Car =

1×2 struct array with fields:

brand

model

consumption

4.3 Exercise

Exercise 14.

Build a structure for the following stocks where each row is a field.

Name Last Price Highest Price Lowest Price VolumeNESTLE 50.62 51.05 50.60 1137511SWATCH 364.20 372.60 360.70 51947SWISS RE 48.24 49.50 48.17 329296

SWISSCOM 350.90 355.50 349.50 61944UBS 11.07 11.41 11.06 4916261ZURICH FINANCIAL 198.20 203.20 198.10 172890

Write a function providing the name of the stock with the highest spread High−Low and taking asinput the structure previously built.

5 General Programming Recommendations

This section gathers recommendations about how to write a Matlab program which is understandableand maintainable by others (and yourself some days later).

5.1 Nomenclature

In order to name a variable or a function, it is common practice to respect the following guidelines:

• all names should be in English

• the name of constants should be uppercase, e.g. MAX ITERATIONS

18

Page 19: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

• the name of a variable is often composed of several words. The usage is to concatenate themwith the first of each word in capital letter, e.g. qualityOfLife. Alternatively, insert anunderscore between two words, e.g. qualityoflife.

• common scratch letters for integers are i, j, k, m, n and for doubles x, y and z

• iterator names should be prefixed with i, e.g. iRows

• the name of structures should begin with a capital letter, e.g. Car.color, Car.model

• functions should have meaningful names

• the prefix is should be used for boolean functions, e.g. isFound(.)

Following these guidelines is greatly appreciated when working in team.

5.2 Comments

The purpose of comments is to add information to the program. You can use it to explain a delicatepart of your program, to explain how to call your functions, etc. Very frequently, functions/scriptsbegin with some lines of comment to explain the goal of the function/script, to describe its inputand output, and to provide information such as the date of programming, the modifications addedand the authorship. All this information is useful to yourself and to your co-workers.

In Matlab, everything following a ′%′ is comment and, as a consequence, it is not executed. Forinstance, in the following example, we have A = 1 because the instruction A = 2 is commented(indeed, it is preceded by ′%′).

Example 39.

>> A = 1 % A = 2

A =

1

In the next example, the comment is used to explain a line of instruction:

Example 40.

X = [ 0 1 0 1 1 1 0 1 0 0 ];

Y = [ 1 1 0 0 0 1 1 1 1 0 ];

X.*Y; % Boolean ’and’ operation.

Remark that, as in other languages, you can also comment a line using \\ instead of %.

Commenting is also useful to ”deactivate” a part of a program without flushing it. In order tocomment some blocks of code, insert it between %{ . . . %}. For instance, in the following example,the for loop is commented and thus is not executed.

19

Page 20: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 41.

X = [ 0 1 2 3 4 5 6 7 8 9 ];

Y = zeros(1, 10);

%{for i=1:10

Y(i) = X(i)^2;

end

%}Z = X + Y;

When you write a function/script, you should introduce it with initial comments. As stated earlier,they have to explain the goal of the function/script, to describe its input and output, and to provideinformation such as the date of programming, the modifications added and the authorship. Theyshould be written as follows:

Example 42.

function MyResults = MySuperFunction( Input1, Input2)

% MySuperFunction: the aim of MySuperFunction is to ...

% Input1: is a double representing ...

% Input2: is a string. It is the name of ...

% MyResults: is a double. It is ...

%% Ludovic Cales, 24/10/2011

Your instructions

5.3 Keep a Readable Code

First, try to write short functions. In this way, it is easier to read and to maintain. In addition,having atomized functions allows you to easily re-use previously implemented functions.

Keep your lines within the usual 80 characters (i.e. within your screen or your printer). If your lineneeds to be longer, then use three dots ′ . . .′ to continue your programming on the next line.

Indent your program inside the loops, as in the previous examples.

5.4 Tests, Errors and Warnings

When you have just written a function, test it before to incorporate it in the whole program. Thistest is called a unitary test. Next, test it by running the whole program. This test is called anintegration test.

When writing a function with input arguments, it is useful to check the type of the input before tocontinue. Indeed, you could use a string instead of a double for instance (see the following example).This mistake would no be immediately identified because a character is a double (internally in Mat-lab). A full range of functions allow you to test these entries: isnumeric(.), isinteger(.), ischar(.),isvector(.), isempty(.), etc.

20

Page 21: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 43.

>> double(’a’)

ans =

97

>> double(’b’)

ans =

98

>> ’a’+’b’

ans =

195

For your testing, it is advised to use the function warning(.) and error(.) to report that somethingis wrong. Warning(.) just displays a warning message and error(.) displays a message, stops thefunction and generates an exception (see Section 6.1 for the definition of an exception). The man-agement of errors and exception are seen in Section ??. An illustration of input check is providedin the following example.

Example 44.

function MyResults = MySuperFunction( Input1, Input2)

% MySuperFunction: the aim of MySuperFunction is to ...

% Input1: is a double representing ...

% Input2: is a string. It is the name of ...

% MyResults: is a double. It is ...

%% Ludovic Cales, 24/10/2011

if (ischar(input1) ∼= 1)

warning(’input1 must be a string’);

end

The rest of your instructions

5.5 Memory Management

First, initialize your variables before to use them and delete them when you don’t need them any-more. It speeds up your programs and you keep a manageable workspace. The pre-allocation ofvariable is illustrated in the next section about optimized programming.

Next, while running some programs, you will encounter the ’out of memory’ error. This is becauseyour program tries to use more memory than your computer has. Try the following example, forinstance.

Example 45.

for i=0:100

S(i*10000000+1:(i+1)*10000000) = ones(10000000,1);

end

You get??? Out of memory. Type HELP MEMORY for your options.

21

Page 22: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

To correctly manage your memory:

• clear unnecessary variables as soon as you won’t use them anymore

• avoid creating temporary variables

• process data by blocks, i.e. slice your data, especially in Monte Carlo methods

Remark that the variables created in a function are deleted at the end of the function call. Inaddition, the functions uses copies of the variables passed in argument. As a consequence, anyvariable passed as argument to a function takes twice its size in memory. In case of very large dataset, consider global variables or proceed by blocks.

5.6 Optimized Programming

There are two main ways to speed up your Matlab code:

1. pre-allocate your arrays

2. vectorize your code

First, the pre-allocation of arrays consists in allocating the memory space that an array requiresbefore to assign it its values. Consider the following example where the arrays ′a′ and ′b′ are notpre-allocated. Indeed, each array is extended by the addition of a new element in each loop. Here,we use the ’tic’ and ’toc’ command to get the time required by the set of instructions between thecall of the ’tic’ and ’toc’ commands. The command ’tic’ resets the counter and the command ’toc’displays the elapsed time since ’tic’ has been called.

Example 46.

tic;

a(1) = 1;

b(1) = 1;

for i=1:10000

a(i+1) = 2*a(i) + b(i);

b(i+1) = 2*b(i) + a(i);

end

toc;

The code in the previous example required 0.161 seconds.

Now consider the following example, providing the same results as before, where the arrays ′a′ and′b′ are pre-allocated.

Example 47.

tic;

a = zeros(10000,1);

b = zeros(10000,1);

a(1) = 1;

b(1) = 1;

for i=1:10000

a(i+1) = 2*a(i) + b(i);

b(i+1) = 2*b(i) + a(i);

end

toc;

1The computer used for this computation has an Intel c©Q9400 2.66Ghz processor and 3.46 Go of RAM.

22

Page 23: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

It takes only 0.003 seconds to Matlab to reach the same results.

Secondly, the vectorization consists in avoiding multiple scalar operations and to prefer matrix op-erations. Mostly it corresponds to convert loops into matrix operations. Consider the following twoexamples where a for loop is vectorized. The code presented here computes the sum of the elementsof the element-wise product of the vectors ′a′ and ′b′.

Example 48.

tic;

a = [1:1000000]’;

b = [1000000:-1:1]’;

mySum = 0;

for i=1:1000000

mySum = mySum + a(i)*b(i);

end

toc;

The previous example is vectorized as follows.

Example 49.

tic;

a = [1:1000000]’;

b = [1000000:-1:1]’;

mySum = a*b’;

toc;

The first example requires 0.025 seconds to be executed. The second one requests only 0.02 seconds.

5.7 Exercise

Exercise 15.

In this exercise, we want to compute the area covered by the following system:{x2 + y2 ≤ 1x+ 2y ≥ −1.5

, with (x, y) ∈ R.

In order to compute this area, we use the so-called Monte-Carlo integration. In consists in drawingrandom numbers covering a known area and to count how many of them respect the constraints. Thisapproach is illustrated below for your system.

23

Page 24: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

In order to compute this area proceed as follows:

1. draw – from the uniform distribution – a n × 2 matrix of random numbers. Transform therandom numbers such that they cover the [−11]× [−11] square which is known to have an areaof 4.

2. count how many of the random numbers respect the constraints of the system. Deduce the areacovered by the system.

In order to provide an accurate approximation of this area consider n = 10.000.000.

6 Error management and Debugging

6.1 Error management

When an error occurs – an index exceeding the dimension of a matrix for instance – an exceptionis generated. An exception is a signal that an exceptional situation cannot be managed in theusual way (for instance with the checks performed in the previous section). Any error generates anexception. The exceptions are caught using the ’try ... catch ...’ command. The general use of the’try ... catch ...’ command is as follows. First, you ’try’ a set of instructions/functions. If theseinstructions/functions generate an exception, the program continues in the ’catch’ section. Remarkthat without the ’try ... catch ...’ command the program would simply stop signaling the error.

Example 50.

try

Set of instruction

catch

Management of the error

end

Here is an example where a set of instructions generating an error is tried and how the exceptiongenerated by this error is caught.

24

Page 25: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 51.

myMatrix = ones(2,3);

try

myResults = myMatrix(5,9);

catch

myResults = 0;

end

In this example, a 2 × 3 matrix of one is created. Then, in the ’try’ section, we want to assignits (5, 9)th element, which does not exist, to myResults. An error ’index out of bound’ is thengenerated. It is caught in the ’catch’ section which assign the value 0 to myResults. The programcan then continue as if no error occurred.

Remark that if you create your own error as in Section 5.4, an exception is generated as for anygeneric Matlab’s errors.

In addition, even though the ’try ... catch ...’ command may prove to be very useful, it is recom-mended to not make an extensive use of it. Indeed, the program is much less readable and it easilyhides the malfunctions.

6.2 Debugging

To ’debug’ is to identify and solve some malfunctions in a program. It consists in setting points,called ’breakpoints’ in your program where to stop and verify the values of your variables. In Mat-lab’s environment, there is a tool dedicated to this purpose in the ’debug’ menu. You can set yourbreakpoints by clicking on the number of the line where you want to stop. Then, still in the editor,run the file by clicking on the ’run’ icon in the ’debug’ menu. The program stops at each ’breakpoints’and you can verify that yours variables behave correctly. Next, to pass to the following ’breakpoints’,just click on the ’continue’ icon.

For instance, in the following example, we set a breakpoint on the line in the loop. Then, by runningthe file, we verify in the workspace that the variables behave correctly.

Example 52.

tic;

a = [1:1000000]’;

b = [1000000:-1:1]’;

mySum = 0;

for i=1:1000000

mySum = mySum + a(i)*b(i);

end

toc;

We can verify that at the first stop we have i = 1 and mySum = 1000000, at the second stop i = 2and mySum = 2999998, etc.

25

Page 26: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

6.3 Exercise

Exercise 16.

Here is a Matlab script which should compute 20!. There is a mistake in the scirpt. Find using thedebugger.

myFactorial = 1;

for i=0:20

myFactorial = myFactorial*i;

end

7 Graph Plotting

7.1 Plot y=f(x)

In order to plot a function y = f(x) with x on the horizontal axis (abscissa) and y on the verticalaxis (ordinate), we use the plot function. This function takes as basic inputs some x-coordinates asa vector X and the respective y-coordinates as a vector Y, and it plots each (x,y) points connectingthem with a line. The function is called by plot(X,Y ). The following example illustrates the use ofthe plot function with X = [−pi : 0.01 : pi]′ and Y = sin(X). This calling opens a figure windowdisplaying the graph.

Example 53.

>> X=[-pi:0.01:pi];

>> Y=sin(X);

>> plot(X,Y);

In this example, plot(X,Y ) provides you with the following figure.

Figure 1: Graph obtained from Example 53

In order to plot several functions in the same figure, we proceed in a similar way. Now, Y is a matrixwhere each column corresponds to a function (in the first example, there was only one function, thusY was a vector). In the following example, we plot both sin(X) and cos(X) where X is defined asin Example 53.

26

Page 27: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 54.

>> X=[-pi:0.01:pi]’;

>> Y=[ sin(X) cos(X)];

>> plot(X,Y);

Here, we obtain the following figure.

Figure 2: Graph obtained from Example 54.

Now, in the case each function has different x-coordinates, we have to provide plot(.) with each Xi

and Yi sequentially, i being the number of functions. In the following example, we provide differentx-coordinates to the sine and cosine functions. Remark that in this case the number of x-coordinatesis not necessarily the same for each function.

Example 55.

>> X1=[-pi:0.02:pi];

>> Y1= sin(X);

>> X2=[-pi+0.01:0.02:pi-0.01];

>> Y2= cos(X);

>> plot(X1,Y1,X2,Y2);

Example 55 provides the following result which is very similar to Example 54.Remark that the same result can be obtained using the hold function which enables to add plots tothe graphs. To use it, enter hold on before to add a plot. Example ?? illustrates the use of hold.

Example 56.

>> X1=[-pi:0.02:pi];

>> Y1= sin(X);

>> X2=[-pi+0.01:0.02:pi-0.01];

>> Y2= cos(X);

>> plot(X1,Y1);

>> hold on;

>> plot(X2,Y2);

To give a title to the graph, use the function title(.) providing it a string with the graph’s title.

27

Page 28: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Figure 3: Graph obtained from Example 55.

Example 57.

>> title(’My sine and cosine graph’);

It is possible to change the text properties such as the font, the font size and the font weight forinstance. In order to change the font, add the arguments ’FontName’ and a string with the name ofa font (e.g. ’courrier’). To change the font size, add the arguments ’FontSize’ and a numeric with thedesired font size (by default it is 10). To change the font weight, add the arguments ’FontWeight’and a string among the following ones: ’light’, ’demi’ and ’bold’. The following example illustrateshow to get a title with font size 18 and bold.

Example 58.

>> title(’My sine and cosine graph’, ’FontSize’, 16, ’FontWeight’, ’bold’);

To give labels to the x- and y-axis, use the function xlabel(.) and ylabel(.) providing them a stringwith the label. The text properties for labels are the same as for titles.

Example 59.

>> xlabel(’X’, ’FontSize’, 14, ’FontWeight’, ’bold’);

>> ylabel(’Y’, ’FontSize’, 14, ’FontWeight’, ’bold’);

To include legends to the graph, use the function legend(.) providing a string for each functiondisplayed. The first string corresponds to the first function, the second string to the second function,etc. The text properties for legends are the same as for titles.

Example 60.

>> legend( ’sine function’, ’cosine function’ );

In order to place the legends in a specific place in the graph, we add the arguments ’Location’ and alocation code to the legend(.) function. Some basic location codes follow. For more location codes,refer to the help.

’NorthEast’ Inside top right (by default)’NorthWest’ Inside top left’SouthEast’ Inside bottom right’SouthWest’ Inside bottom left

28

Page 29: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

To include the legends in the top left corner of the graph, it is implemented as follows:

Example 61.

>> legend( ’sine function’, ’cosine function’, ’Location’, ’NorthWest’ );

Examples 58, 59 and 61 lead to the following additions to Graph 3.

Figure 4: Graph obtained from Example 55 with additions of a tittle, axis labels and legend asillustrated in Examples 58, 59 and 61.

In addition, to fix the boundaries of the x- and y-coordinates, we use the functions xlim(.) andylim(.). These functions take as input a vector with two elements: the lower limit and the upperlimit of the axis. For instance, to enlarge the previous plot on the the y-axis (Figure 4), we proceedas follows.

Example 62.

>> ylim( [-1.2 1.2 ] );

It results in the following graph where the boundaries pass from 1 to 1.2 on the y-axis.

Figure 5: Graph obtained enlarging the y-axis of Figure 4 by proceeding as described in Example62

29

Page 30: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Another useful plotting tool is the grid. The function grid depicts a grid on the graph. It displaysa grid where each line springs from a label of each axis. The grid is displayed by grid on and erasedwith grid off. Continuing with previous example, we display the grid proceeding as follows.

Example 63.

>> grid on;

The resulting graph is following.

Figure 6: Graph obtained by displaying the grid on Figure 5 as illustrined in Example 63.

To add information to the graph, we use the function annotation(.). This function takes as input :the type of annotation (usually ’textarrow’), the vector of x-coordinates of the starting and endingpoints of the arrow (x1, x2), the vector of y-coordinates of its starting and ending points (y1, y2),the property name ’string’ followed by the string of annotation. Remark that the (x, y) coordinatesprovided here are normalized to the graph such that the bottom left and top right corners of thegraph have coordinates (0, 0) and (1, 1) respectively. For instance, in the previous graph, supposeyou want to highlight the points where sin(x) = cos(x). Then, you proceed as follows. First, drawa text arrow to one point with the accompanying text. Next, add a second arrow with no text as italready has been displayed.

Example 64.

>> annotation(’textarrow’, [0.3 0.59], [0.6 0.75], ’string’, ’sin(x)=cos(x)’);

>> annotation(’textarrow’, [0.3 0.29], [0.6 0.28]);

The result is following in Figure 7.

Other types of annotation are available such as text only, using the annotation type ’textbox’, thetwo headed arrow with ’doublearrow’, etc. The properties of text of the annotation, such as the fontsize, can be modified as the title.

Now, let consider the scale of the axis. For instance, in the previous graph, it corresponds to thelabels −4, −3, −2, −1, 0, 1, 2, 3 and 4 on the x-axis and to the labels −1 to 1, by steps of 0.2 onthe y-axis. In Matlab, the scale is defined and labelized automatically. In the case of x-coordinatescorresponding to dates, for instance with time series, the scale is indexed from 1 to n, where n isthe number of elements plotted. Automatically, the scale uses these indices as labels. However, thedefault scale can be replaced by a customized one and associated labels. This is performed using thefunction set(.) which modifies the properties of the figure. This function set(.) takes as first input the

30

Page 31: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Figure 7: Graph obtained displaying annotation on Figure 6.

current figure handle, gca, and the property names followed by their associated array. The currentfigure handle, gca, will be studied later with the Graphic User Interface. The property name ’XTick’refers to the indices to place on the scale and the property name ’XTickLabel’ refers to the associ-ated labels. The number of indices placed on the scale and the number of labels have to be the same.

For instance, consider the plotting of a time series myTimeSeries of 12 prices, one for each monthof a year starting with January. To display months as labels of the time series’ plot, proceed asfollows. Build your arrays, display the graph and then modify the labels using the function set(.).Here, we add a grid for a better readability.

Example 65.

>> myTimeSeries=[0.012 ; -0.007 ; 0.009 ; 0.018 ; 0.006 ; -0.003; -0.021; -0.014 ; -0.008 ; -0.005 ; 0.002 ; 0.007];

>> myLabels = {’Jan.’, ’Feb.’, ’Mar.’, ’Apr.’,’May.’, ’June’, ’July’, ’Aug.’, ’Sep.’, ’Oct.’, ’Nov.’,’Dec.’};>> plot(myTimeSeries );

>> set(gca, ’XTick’, 1:12, ’XTickLabel’, myLabels);

>> grid on;

Example 65 leads to the following graph.

Figure 8: Graph displaying customized labels obtained from Example 65.

Remark that we can display only one out of two labels by selecting the indices to display on the scalewith ’XTick’. The labels displayed with ’XTickLabel’ have to match this selection. The following

31

Page 32: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

example illustrates this display of one out of two labels.

Example 66.

>> myTimeSeries=[0.012 ; -0.007 ; 0.009 ; 0.018 ; 0.006 ; -0.003; -0.021; -0.014 ; -0.008 ; -0.005 ; 0.002 ; 0.007];

>> myLabels = {’Jan.’,, ’Mar.’, ,’May.’, ’July’, ’Sep.’, ’Nov.’};>> plot(myTimeSeries );

>> set(gca, ’XTick’, 1:2:12, ’XTickLabel’, myLabels);

>> grid on;

The resulting graph follows in Figure 9.

Figure 9: Graph displaying customized labels obtained from Example 65.

In the same way, the scale of the y-coordinates is modified using the arguments ’YTick’ and ’YT-ickLabel’ in the plot function.

7.2 Scatter plot

The scatter plot is another type of graph. Unlike plot(.) which connects two successive points,the scatter(.) function displays points at (x, y) coordinates. It takes as basic input the vector ofx-coordinates and the vector of y-coordinates. For instance, suppose that you want to display thefollowing points x1 = (0.1, 0.2), x2 = (0.6, 1.3), x3 = (1.1, 0.4), x4 = (1.4, 0.9), x5 = (1.2, 1.6),x6 = (1.8, 0.3) and x7 = (0.7, 1.2). First, you first build a vector with the x-coordinates of thepoints, followed by a vector of its respective y-coordinates. Then, you call the function scatter(.)with these vectors as input.

Example 67.

>> X = [ 0.1 0.6 1.1 1.4 1.2 1.8 0.7 ];

>> Y = [ 0.2 1.3 0.4 0.9 1.6 0.3 1.2 ];

>> scatter(X,Y);

It provides you the following graph in Figure 10.

32

Page 33: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Figure 10: Scatter graph obtained from Example 67.

You can add titles, labels, legends, limits, grids and annotations in the same way as plot graphs.

7.3 Plot histograms

The histogram plot is another type of graph. Considering a given vector, it displays the number ofelements of this vector whose values lie within successive intervals (bins). The function to displaysuch a graph is hist(.). As input, it takes a vector. Optionally, you can enter the number of binsto display as an integer or, alternatively, a vector defining the centers of the bins. By default, thenumber of bins is 10 and the graph includes the minimum and maximum values of the input vector.

For instance, considering the vector of random values X = randn(10000, 1), the following histogramdisplays the number of elements in each of 20 equally spaced bins, between the minimum andmaximum of X.

Example 68.

>> X=randn(10000,1);

>> hist(X,20);

Example 68 provides us the following graph.

Figure 11: Histogram obtained from Example 68.

33

Page 34: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Alternatively, the bins can be defined by providing the vector of the bins’ centers as second input.Remark that, in this way, the frontier between two bins is equi-distant to each adjacent centers andthat the centers do not have to be equally spaced. The following example illustres the use of nonequally spaced centers.

Example 69.

>> X = randn(10000,1);

>> bins = [ -4 -3 -2 -1 0 2 5 ];

>> hist(X,bins);

Example 69 provides us the following graph.

Figure 12: Histogram obtained from Example 69.

8 Optimization

8.1 Function handle

The optimization functions studied in the following sections take the function to optimize as aninput. However a function is not a variable, so it needs to be transformed into a variable to behandled and passed as an input to another function. In Matlab, this transformation is possible bypassing a function into the function handle data type. The handle of any function, i.e. the variablein the function handle data type, is simply obtained with the ’at’ sign (@) followed by the functionname, and can be named as any other variable. It general syntax is

myV ariable = @FunctionName (8.1)

where FunctionName is the name of the function to manipulate and myVariable is the handleof the function. For instance, a function handle for the cosine function – named cos in Matlab – isbuilt as follows.

Example 70.

>> myCosineHandle = @cos;

Now, the variable myCosineHandle can be passed in argument to another function. Remark thatthe function handle is not used to call the related function but to handle it as simply as any othervariable.

34

Page 35: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

8.2 Solving an Equation with fsolve(.)

In this section, we introduce the function fsolve(.) to solve a problem of the type f(X) = ~0 whereX is a vector and f(X) returns a vector.

The general syntax of this function is

[X, fval, exitflag] = fsolve(myfcthandle,X0) (8.2)

where

myfcthandle corresponds to the function handle of f , the function to solve.X0 is a vector of initial values, corresponding to the point where the algorithm begins its search.exitflag describes the algorithm termination: > 0 , succeeded,

< 0 , failed,0 , did not end (e.g. it reaches the max.

number of iterations),X is the solution vector which might not be unique.fval returns the value of the function f in X. Due to tolerance (precision)

in the solution, it might not be ~0

Example 71.

Consider the function f(x) = 2x5 + 3x4 − 30x3 − 57x2 − 2x + 24. First, write a .m file for yourfunction.

function y = myFunction(x)

y = 2*x.5 + 3*x.4 - 30*x.3 - 57*x.2 - 2*x + 24

end

Next, plot its graph on the [−4, 4.1] interval to have an idea of the function.

>> plot([-4:0.01:4.1], myFunction(-4:0.01:4.1]));

>> grid on;

Then, to find one root of the polynomial, use the fsolve(.) function providing it with an initial value.

>> [X , fval, exitflag] = fsolve(@myFunction,0)

X =

0.56

fval =

-3.324e-009

exitflag =

1

Remark that by changing the initial value, the solution may change. Indeed, this polynomial hasfive roots. For instance, by providing as initial value −2, we get the root −1.5.

It is possible to avoid using the function handle and provide to fsolve(.) the name of the functionas a string (Example 72) or, if the function is an inline function, you can provide directly the nameof the function as input (Example 73). However, such proceedings are restrictive and do not allowto add parameters to the function as it will be seen in Section 8.6.

35

Page 36: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 72.

Here, we consider the function myFunction(.) provided in a .m file as in example 71.

>> [X , fval, exitflag] = fsolve(’myFunction’,0)

Example 73.

>> myInlineFun = inline(’2*x.5 + 3*x.4 - 30*x.3 - 57*x.2 - 2*x + 24’, ’x’);

>> [X , fval, exitflag] = fsolve(myInlineFun,0)

8.3 Optimizing Unconstrained Problems with fminsearch(.)

In this section, we introduce the function fminsearch(.) to find the minimum of a multivariate func-tion returning a scalar.

Its general syntax is the same as for fsolve(.), i.e.

[X, fval, exitflag] = fminsearch(myfcthandle,X0) (8.3)

where the arguments are those of the previous section.

As an illustration, consider the following example where we find the minimum of f(x, y) = x2 + (y−2)2, the bowl function. This function is illustrated in Figure 13.

Figure 13: Surface and contour plots of the Bowl function.

Example 74.

First, write an .m file for the bowl function.

function z = Bowl(x)

z = x(1)ˆ2 + (x(2) -2)ˆ2;end

Then, call fminsearch(.) as follows

36

Page 37: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

>> [ X , fval , exitflag ] = fminsearch(@Bowl, [ 1 1 ]);

X =-0.0000 2

fval =2.7371e-009

exitflag =1

Indeed, the solution is (0, 2).

8.4 Optimizing Constrained Problems with fmincon(.)

In this section, we introduce the function fmincon(.) to find the minimum of a multivariate func-tion returning a scalar when the variables are subject to some constraints. Consider the followingproblem:

minxf(x) subject to

∣∣∣∣∣∣∣∣∣∣c(x) ≤ 0ceq(x) = 0A x ≤ bAeq x = beqlb ≤ x ≤ ub

(8.4)

where c(x) and ceq(x) are non-linear functions, A and Aeq are matrices, b, beq, lb and ub are vectors.

Given the previous problem, the general syntax to call fmincon(.) is

[X, fval, exitflag] = fmincon(myfcthandle,X0, A, b, Aeq, beq, lb, ub, nonlcon) (8.5)

where the arguments myfhandle and X0 are those of the previous sections, the parameter nonlcondefines the functions c(x) and ceq(x), and the parameters A, b, Aeq, beq, lb and ub are those givenby the problem.

If some input arguments do not apply, set them to [ ] as shown in the following example.As an illustration of the use of fmincon(.), consider the following example where we want to findthe minimum of f(x, y) = (x2 + y− 11)2 + (x+ y2 − 7)2, the Himmelblau function. This function isillustrated in Figure 14

Figure 14: Surface and contour plots of the Himmelblau function.

This function has four minima. We can select a desired domain for the minimum by imposingconstraints on x and y. In the following, we look for a minimum such that x < 0 and y > 0, i.e. inthe top left corner of the figure.

37

Page 38: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 75.

First, write an .m file for the Himmelblau function.

function z = Himmelblau(x)

z = (x(1)ˆ 2+x(2)-11)ˆ 2 + (x(1)+x(2)ˆ 2-7)ˆ 2;

end

Here, the system implied by the constraints is[1 00 −1

]︸ ︷︷ ︸

A

[xy

]≤[

00

]︸ ︷︷ ︸

b

(8.6)

So, we define the parameters A and b as follows.

>> A = [ 1 0 ; 0 -1];

>> b = [ 0 ; 0 ];

Finally, call fmincon(.) as follows

>> [ X , fval , exitflag ] = fmincon(@Himmelblau, [ -1 1 ], A, b, [], [], [], [], []);

X =-2.8050 3.1313

fval =4.0509e-007

exitflag =5

The exitflag is 5, i.e. positive, so the algorithm succeeded in finding a solution. Indeed, (−2.8050, 3.1313)is a solution to this problem.

8.5 Additional Optimization parameters

It is possible to modify some of the algorithm parameters with the optimset(.) function. This func-tion takes as input a parameter name as a string followed by the value assigned to this parameter.Here are the most commonly used parameters: the number of iteration performed by the algorithm’MaxIter’ (1000 by default), the precision desired for the result returned by the objective function’TolFun’ (10−6 by default) and the precision desired for the variables ’TolX’ (10−6 by default). Theoptimset(.) function returns a structure which is then provided as last argument to the functionsfsolve(.), fminsearch(.) and fmincon(.).

The general syntax of optimset(.) is

options = optimset(′ParameterName1′, value1,′ ParameterName2′, value2, . . . ) (8.7)

For instance, in Example 74, we increase the precision on the objective function’s return as follows

38

Page 39: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Example 76.

>> options = optimset( ’TolFun’, 1e-10);

>> [ X , fval , exitflag ] = fminsearch(@Bowl, [ 1 1 ], options);

X =0.0000 2

fval =4.5577e-012

exitflag =1

Indeed, while the theoretical value of the bowl function in (0, 2) is 0, it has found fval = 4.5577e−012 < 1e− 10. It is more precise than in Example 74.

8.6 Passing Extra Parameters to the Objective Function

Suppose that your objective function takes some parameters you want to be variable in additionto the unknown variables. For instance, consider the function f(x) = ax2 + bx + c where x is theunknown and, a, b and c are parameters. The .m file of this function would be

Example 77.

function y = mypolynomial(x, a, b, c)

y = a*xˆ2 + b ∗ x+ cend

Now, to pass these three parameters as input of the function while minimizing it, we use the functionhandle precising which input is the variable.

For instance, to find the minimum of mypolynomial(.) using fminsearch(.), we proceed as follows

Example 78.

>> a=1;

>> b=2;

>> c=1;

>> [ X , fval , exitflag ] = fminsearch(@(x)mypolynomial(x, a, b, c), 1);

8.7 Exercises

Exercise 17.

Find the minimum of f(x, y) = (1−x)2 +100∗ (y−x2)2. It corresponds to Rosenbrock’s functionillustrated bellow.

39

Page 40: Introduction to Matlab Programming - HEC UNIL · PDF fileIntroduction to Matlab Programming Ludovic Cal es November 8, 2012 Abstract This course is designed to make the students autonomous

Figure 15: Surface and contour plots of Rosenbrock’s function.

Exercise 18.

Find the minimum of f(x, y) = 20+x2+y2−10 (cos 2πx+ cos 2πy). It corresponds to Rastrigin’sfunction illustrated bellow.

Figure 16: Surface and contour plots of Rastrigin’s function.

40