0% found this document useful (0 votes)
35 views79 pages

1 - Intro Matlab

Introduction to Matlab

Uploaded by

Vincenzo Cassone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views79 pages

1 - Intro Matlab

Introduction to Matlab

Uploaded by

Vincenzo Cassone
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

LAB OF SOFTWARE

APPLICATION FOR FINANCE


[LABEFF]
LAB OF SOFTWARE
APPLICATION FOR ECONOMICS
[LABEFE]

Prof. A.M. D’Arcangelis [email protected]


Prof. Roeland De Kok [email protected]
23/9/2021 - 30/9/2021
Lesson 1 + Lesson 2
https://it.mathworks.com/academia/books/matlab-per-le-applicazioni-economiche-e-finanziarie-
pocci.html
https://www.amazon.it/Matlab-applicazioni-economiche-finanziarie-
Cristina/dp/8891619922/ref=sr_1_1?__mk_it_IT=%C3%85M%C3%85%C5%BD%C3%95%C3%91&dchild=1&keywords
=rotundo&qid=1600067358&s=books&sr=1-1
Introduction to computer
programming languages
Organization of
Software interface
the course Main commands
First part: introduction to
software and basic and
advanced instructions in
Matlab and Python.
Part two: applications to
economic and financial models

Organization of
the course Learning objectives:

Model/software management

Autonomous programming
Introduction to programming languages (1/5)
Why «languages»?
• Because it is a way to communicate to the computer what it has to
do.
• Keywords are special words which correspond to specific
operations.
• Data are needed as well.
• The way in which the instructions are put together has the same
structure of a language (syntax, spelling).

What is a program?
• It is a set of instructions targeted to reach a result

• Base concepts of computer programming (instructions, iteration,


conditional choice)
Introduction to programming languages (2/5)

All programming languages are based on fundamental


constructs:
Sequences, conditions and cycles (Section 1.9, p.14)
Sequences: series of executive instructions, that
explicitly ask the computer to perform operations
Example:
a=2+exp(5);
save a
(the computer calculates the value of a and saves it)
Introduction to programming languages (3/5)
Conditional choice: some instructions are executed (or
not) depending on a (or some) condition(s). The main
instruction is if (p.78 book Matlab)

Matlab example:
VBA: d=10;b=5;c=3;
d=10;b=5;c=3;
if (d>b) then
if (d>b) c=10;
c=10; End If
end
(d>b) is the condition.

if and end (Matlab) (or End If (VBA) and Then (VBA) are keywords.
The spelling is relevant.
All the instruction between if and end (Matlab) or End If (VBA) are
executed only if the condition is true.
In the Example, if d>b (which happens with d=10 and b=5), then c is
set equal to 10. Otherwise, c would have remained equal to 3.
Introduction to programming languages (4/5)
Matlab Example:
d=10;b=5;c=3;
if (d>b)
c=10;
end

In the example
➢if the value contained in d is greater than the value contained in b
(which is verified with the assigned values of b and d) then c is
assigned the value 10.
➢otherwise c would have remained equal to 3.
Introduction to programming languages (5/5)

➢Iterations: group of instructions repeated till a


condition is verified (ending condition).

➢Main structures: for and while (Section 3.5 pp. 75.78


book Matlab)

➢for executes the instructions only a fixed number of


times (the iteration ends when the number of times
in which the code is executed is greater than the
fixed maximum limit).

➢while is more flexible on the ending condition, which


has to be written.
Getting started
The Matlab interface
Matlab is a software language for scientific calculus that integrates functions of calculus, graphic
visualization and computer programming. It is implemented in a powerful work environment with a
graphical user interface and a modular structure that makes its functionality considerably
expandable. This is the user interface at the opening.

Help: access to the


Getting started
The current folder is a instruction manual
reference location that
MATLAB uses to find files.
This folder is sometimes
referred to as the current
directory, current working
folder, or present working The line that starts with >> is the
directory.
command line.
Giving a command to MATLAB means
writing appropriate instructions on this
line and pressing the enter key.
How to write ‘proper instructions’ on the
command line in MATLAB?
1. A set of 'appropriate instructions', written in
an appropriate language, constitutes a
MATLAB command.
2. The language is a set of formal rules for
writing commands
3. More instructions can be written in the
same line, separating them with ;
4. Matlab instructions are called 'executable'
because they tell MATLAB what operations
to perform and are 'interpreted', i.e.
translated into machine code and executed
immediately.
Let's see how to use MATLAB as an advanced calculator
Matlab as an advanced calculator …
•It is the most immediate way to use the software.
2
For instance, for calculating 4 + 2 − 𝑠𝑖𝑛 0.2𝜋 + 𝑒2
type on the Command window: 4+sqrt(2) –
sin(0.2*pi)^2 + exp(2) and press Enter.

•The result is in ans (short for answer).

•Example:

Instructions typed by the


user

Result printed by MATLAB.


ans = is an abbreviation for
'answer'.
Open the Command History Window
The command history To open the Command History window with all
history showing, in the Command Window,
press the Up Arrow key (↑) or enter
commandhistory.

Lists all the commands already executed

Command History Window Description


The Command History window displays a log of statements that you ran in the current and previous MATLAB® sessions. The Command
History lists the time and date of each session in the short date format for your operating system, followed by the statements from that
session. Brackets in the left margin indicate statements that were processed as a group. A colored mark precedes each statement that
generated an error.

MATLAB saves statements that run in the Command Window to the history file History.xml. These statements include those you run using
the Evaluate Selection item on context menus in tools such as the Editor, Command History window, and Help browser. By default,
MATLAB automatically saves the command history file after each statement. The history file does not include every action taken in
MATLAB. For example, changes to values in the Variables editor are not included in the Command History window. All entries remain
until you delete them, or until the number of statements in the history file exceeds the number of statements to save, as specified in the
Command History preferences. When the specified limit is reached, MATLAB automatically deletes the oldest entries. By default, the
Command History window saves 25,000 statements.
The Current folder
Lists the files in the current directory.
Automatically, Matlab is placed on the directory Documenti/Matlab.
The files should all be saved there.

MATLAB INTERFACE

My folder
Documenti / Matlab
The editor
Steps to follow:
Write the program in the editor
Save with Save as giving a name (I
gave ScriptIf)
Run with Run (does not run if you
have not given the name, but notifies
you)

If the editor is not open you can open it by clicking on "New / script": in the editor you
open a program (untitled, name that you can change), the program written in the editor
and active (you may have written many programs) is run by clicking on the green arrow.
Alternatively, you can run a script by typing the name of the file on the command line.
Problem: How to use already calculated values?
MATLAB does not allow you to modify commands that have already been
executed.
These can be called up on the command line by pressing 'up arrow' several
times, or by clicking on the relevant command in the 'Command history'
window (if it appears);
Or, if you think that a value serves later you can store it in a variable that
you can easily recall:

•A variable is represented by a name and –of course– can


change the value associated with it.
•To assign the value to a variable you must use an
expression of the type
• variable = expression
•The expression is calculated and the result is entered into
the variable.

The symbol of = is called the assignment operator because its meaning is


that whatever is calculated on the right is taken and entered into "variable"
that is on the left. IT DOESN'T MEAN =!
Defining Variables
It is possible to define variables (and also more complex non-
numerical expressions) and use them for further calculations.
Example: assign a value to variable a, one to variable b and use
them to calculate the product:

Instructions typed
by the user

Result printed by MATLAB.


‘ans=‘is short for 'answer'.

N.B.: if the command is followed by semicolon ; the calculation is made,


but nothing is printed
Exercise
Write instructions to calculate the sum of the numbers 100, 10, 2
and divide it by 3.
Possible solution:
a=100+10+2;
b=a/3;

Remark: there are rules for writing variable names: Cannot contain
special characters (?,!,$,%,*, spazi intermedi, ecc.) and they can't start
with a number.

Matlab is case sensitive.


The Workspace
Each variable defined in this way is kept in memory,
in the Workspace.
To see a list of defined variables, type whos, or
select Workspace.
To clear a variable, such as a, type clear a.
The numbers
MATLAB considers numbers as

Integer numbers (integers in the usual sense of mathematics): 1, 2,


3,…

2. Real numbers (numbers with decimal places) represented by

A. floating-point notation

to see 16 digits on the screen type format long

to see on the screen 5 digits type format short

B. exponential notation:

type format long e

or format short e
Exercise Type on the command line >>

pi

format long
pi

format short
pi

format long e
pi

format short e
pi
Script files

Instead of typing all the commands on the command


line every time, MATLAB allows you to store them in a
file.
You can get all the commands in the file to run by
typing their name on the command line: all the
instructions written inside will be executed.
The file will automatically get the extension .m and will
be saved in directory ‘Documenti/MATLAB’.
The file can be written through the Editor. It can be
called through ‘edit filename’.
In the file you can insert comments: just start the line
that contains the comment with the symbol %
Order of execution of operations
Elevation to power (symbol ^) is performed first
Multiplication and division are performed immediately
after
Addition and subtraction are performed last.

Exercise: Determine the result of

>>5*2^3-1

and

>>(5*2)^(3-1)
Vectors and Matrices
The mathematical structure on which Matlab is based is the matrix: in Matlab
even a scalar is a matrix... size 1x1.
It is no coincidence that Matlab is the short for MATrix LABoratory.
For example, typing x = 2.45, we have declared the variable x and we assigned it
the value 2.45.
the omission of the semicolon means that the contents of the variable are viewed
on the screen x.
Matlab only manipulates matrices, and in fact an inspection at the Workspace
reveals that x is an array of size 1x1.
Row vector (any length)
It starts with an open square bracket and ends with a
closed square bracket.
Elements are separated either with gaps or with
commas.
Example
>>[ 1 2 3 4];
>>[1,2,3,4];
They are the same row vector. to store it in the v
variable type
>> v=[1 2 3 4];

The length(v) statement returns the length of the


vector.
Column vector
Starts with an open square bracket, ends with a closed
square bracket
Elements within are separated either by starting a new
line or by semicolon ;
Example
>>[ 1
2
3 Does not require to be
aligned
4];
>>[1;2;3;4];
They are the same column vector. To store it in v
>> v=[1 ;2; 3; 4];
also in this case the length(v) statement returns the
length of the vector
Column vector
Accessing the components of a
vector
It follows the usual language
of Mathematics.
The first component of the
vector corresponds to v(1),
the II to v(2),…, the last to
v(end)
For example:

v=[5, 20, 30, 40, 50];


v(1)
>> ans
5
v(2)
>> ans
20
Accessing the components of a vector
Further example:

>>v= [30, 41, 12, 15];


v(2)
ans
41
>> v(1)+v(4)
ans
45
Components can be changed individually

For example
v(1)=100
disp(v)
100 20 30 40 50

The I component is now worth 100

REMINDER: MATLAB IS CASe SensiTIVE


Matrices  a11

a12  a1m 

 a 21 a 22  a2m 
An array or matrix is a table A =  a31 a32  a 3m 
 
with n rows and m columns      
a  a nm 
Example: A is a 3x3 matrix  n1 an2

>> A=[ 1 2 3 This is typed by the


456 user
7 8 9 ];

A=
123
456
789
Other ways of assigning an array

>>A=[1 2 3; 4 5 6; 7 8 9]
>>A=[1, 2, 3; 4 , 5 , 6; 7 , 8, 9]
>> A=[1, 2, 3 space quantity
4, 5, 6 is not
7, 8, 9] important.
You always get the same result:
A=
1 2 3
4 5 6
7 8 9
Matrix Multiplication NOTE: the transpose of c is c’

Multiply a 1x3 row vector by a 3x1 column vector (inner product)

Inner dimensions must be equal!

!! Becomes 3x1
1x3*1x3 error ! Check the innersize of your matrix before executing!

2x3*3x1 ok !
Further instructions
Identity (identical) matrix order n
eye(n)
>>A = eye(3)
A=
100
010
001
Sub-matrix of the identical matrix
eye(n,m)
>>A= eye(2,3)
A= PAY ATTENTION
100 MATLAB DISTINGUISHES
010 UPPERCASE AND
LOWERCASE
Further instructions ZERO MATRIX ALL ZEROS
zeros(n)
>>A= zeros(3)
A=
0 0 0
0 0 0
0 0 0
VECTOR WITH COLUMN OF ZERO
zeros(n,1)
>>v=zeros(3,1)
v=
0
0
0
Further instructions
Construct a zero matrix anywhere and with the vector v
on the diagonal:
A=diag(v)

>>v=[1 2 3];
A= diag(v)
A=
100
020
003
oppure
A=diag([1 2 3]);
Definition of vectors.

In Matlab, you can define vectors of equispaced


points with arbitrarily large dimensions. You
can use the instruction:
x = begin : step : end
This defines a row vector of equally spaced
points starting from begin and ending in end
For example, x = 1 : 1 : 10;
Write an array
A=[1 2 3;4 5 6;1 0 3];
Scrivere un vettore riga,
Examples colonna
and
exercises eyes(n,m): submatrix of the
identical matrix
vectors zeros(n,m): null matrix
and zeros(n,1): column vector
norm(v) : norm 2 of vector v (in
matrices the example=sqrt(14))
norm(v,1) : norm 1 of the vector
v (in the example = 6)
A’ calculates the transposed
matrix
A*B calculates the product of
the matrices A e B
Examples A*v calculates the product of
and matrix A for vector v
exercises inv(A) calculate the inverse of
A
vectors eig(A) calculates the
and eigenvalues of A
matrices [V,D] = eig(A) calculates
eigenvalues (in D) and
eigenvectors (in V) such that
A*V = V*D
mean(v)calculates the average
of the values contained in v
Further std(v) calculates the standard
operations deviation
with A' calculates the transposed
vectors and matrix
matrices A*B calculates the product of
matrices A and B
A*v calculates the product of
matrix A for vector v
Write an m-file (script file) that

Stores in vector v the marks of


the exams taken
Calculates the average
Exercise Divide it by 30
Multiply it by 110
(Hint: The mean(v) statement
averages the elements contained
in vector v)
Write the array to an m-
file
A= [1 3 4; 5 6 7; 6 7 8];
Write the vector as well
v=[1; 2; 3];
Exercise Calculate the product A*v
Calculate v'*(A*v)
Is the result a number, a
vector (>1x1) or
another matrix (> 1x1)
= what is the dimension
of the outcome ?
3x3*3*1
1x3*(3x3*3x1)

4
6
Solve a linear system Ax=b
Case in which theorem and
Cramer's rule are valid: square
matrix, non-zero determinant
MATLAB explicitly calculate the
solution
X=inv(A)*b
Example:
A=[2 6; 4 3]; b=[3;1];
Calculation det(A), check that is
not zero, then I perform
x=inv(A)*b and get the result.

https://www.andreaminini.org/matematica/algebra-
lineare/teorema-di-cramer
ALWAYS ON VECTORS AND MATRICES
REMIND
The presence of a point among the vector and the operation to
be executed means that the operation is done on each single
component of the vector.

Example:
x=[1,2,3];
x.^2 gives [1,4,9]
But x^2 gives error because it tries to multiply a vector 1x3 by
a vector 1x3 (the number of columns of the I is different from
the number or rows of the II, so the product cannot be done).
https://www.mathworks.com/academia/tah-portal/luiss-31077355.html
Download Matlab from the Luiss website
Replicate all the examples, in case of doubt
write me to [email protected]

Have a good week, see you on Thursday 30/9


Other free software
Octave by large extent compatibile with Matlab
https://www.gnu.org/software/octave/
Matlab functions

y=f(x)

y is the result x is the scope


of the function

y=f(x)

function [output1, output2, … ] =funzione (input1, input2,…)

Input:
Output: results scope of the function
Functions M-file (Matlab files .m)

function [output1, output2, … ] = fun (input1, input2,…)

Write here the instructions to calculate


output1, output2, etc. by using input1, input2, etc.

Example: Type on the Matlab command line


Save as quadrato.m: >>x=2;
>> y=quadrato(x)
function f=quadrato(x)
%calculates the square of x y=4
f=x.^2;
Functions M-file (Matlab files .m)
Functions are created in the Editor
Try to create a function in Command Window and tell me...

REMARK: THERE IS NO NEED TO CLOSE THE FUNCTION


WITH «END»; it makes some difference only when you
like to write more functions and executable text in the
same file. However, it is not forbidden.
Usage of functions in calculus

• Functions can be used directly in the calculus


• For instance:
>> 3 *quadrato(x)+1
ans = 13
Functions of more than one variable
We are going to use mainly two kind of input
1) Writing x and y as separed variables (for the 3D
surfaces)
2) Gather all the variables in a vector x (for
constrained optimization)
Vectorial output
Example: write a function that has a vector as output.

Input z=[1;2]
Output
Value of the first component of the vector:
f(z)=z’*V*z, with V=[ 1 2; 3 4];
Value of the second component of the vector:
f(z)=z(1)-exp(z(2));

Solution I function on the I line


function f=fun(z) II function on the II line

f=[z’*V*z
z(1)-exp(z(2))];
Vectorial output
Example: write a function which gives:
I output: the same as before
II output: g(z)=z(1)-(z(2))^2;

Solution
function [f,g]=fun(z)
f=[z’*V*z
z(1)-exp(z(2))];
g=[z(1)-(z(2))^2];
Figure
(2D, 3D, vertical section)

Plot 2D
Plot 3D
Restriction
Histograms
Figure
(2D, 3D, vertical section)

Plot 2D
Plot 3D
Restriction
Histograms
2D Figures
Couples of coordinates are needed.
Example:
x=1:1:10;
y=x.^2; %square of each component
plot(x,y);
Further parameters for plot: color
The first letter of the english name of the color is used (apart
from black, for which the letter is k, so to avoid overlaps with
blue)
Examples: type
plot(x,y, 'k'); %black
plot(x,y, 'b'); % blu
plot(x,y, 'y'); %yellow
plot(x,y, 'r'); %red
plot(x,y, 'm'); %magenta
plot(x,y, 'g'); %green
Further parameters for plot: line
-Continuous line
: dotted line
.- alternating dot and line
It can be combined with the color code.

Examples
plot(x,y,’k-’); %black with continuous line
plot(x,y,’r:’); %red with dotted line
plot(x,y,’g.-’); %green with dot-line pattern
Plot of more functions in the same draw
Two ways:
1) Write «hold on» between the plots. It is sufficient to write it
one time. To stop its effect it is sufficient to type «hold off»
Example:
plot(x,y, 'k'); %black
hold on
plot(x,x.^3,’r’);
plot (x,1./x,’g’);
hold off
2) Couples of coordinates into the same instruction plot.
Example:
plot(x,y,'k’,x,x.^3,’r’,x,1./x,’g’);
Plot of more functions in the same draw
Example:
x=1:1:10;
Y=x.^2; %square of each component
plot(x,y,'k‘,x,x.^3,’r’,x,1./x,’g’);
Histograms
Hist counts how
many values fall in
the bins.

v=[5 5 1 2 5 1 2 3 7 5 6 9 10];
[y,x]=hist(v)
bar(x,y/sum(y))
More data = better histogram
v=randn(10,1);
[y,x]=hist(v);
bar(x,y/sum(y))

The more is the length of the


data, the closer the plot is to the
theoretical Gaussian function.

v=randn(100000,1);
[y,x]=hist(v);
bar(x,y/sum(y))
3 D graphs
Matlab needs a grid to plot the surface. Example:
Given x = [-1:0.1:1] and y=[0:0.1:2];
Build the grid through meshgrid:

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

Now the function can be calculated and drawn:


Example
x = [-2:0.1:2]; %select the x
y = [-2:0.1:2]; %select the y
[X,Y] = meshgrid (x,y); %create the grid
f = exp (-X.^2-Y.^2); %calculate the function on the grid
%Now I have all the values for drawing the surface:
surf (X,Y,f)
surfc
3D draws and curves on the Oxy plane
Example:
x=[-0.5:0.1:0.5];y=x;[X,Y]=meshgrid(x,y);
f=exp(-(X.^2+Y.^2));surfc(X,Y,f)

Exercise: type
[X,Y,Z] = peaks(30);
surfc(X,Y,Z)
colormap hsv
Insert labels on the axes
Another example
Draw contour lines

Example:
x = [-2:0.1:2]
y = [-2:0.1:2]
[X,Y] = meshgrid (x,y)
f = (X.^2+Y.^2)+5
surfc (X,Y,f)
Rotate the 3D figures
Try the icons

rotate
Color palette
(color palette) through colormap. Example:
colormap(jet)
x=[-1:0.1:1];
y=[0:0.1:2]; 1

[X,Y]=meshgrid(x,y);
0.8

0.6

0.4

f=exp(-(X.^2+Y.^2));surf(X,Y,f)
0.2

0
2
1.5 1
1 0.5
0
0.5 -0.5
0 -1

colormap(gray)
x=[-1:0.1:1]; 1

y=[0:0.1:2];
0.8

0.6

0.4

[X,Y]=meshgrid(x,y);
0.2

0
2
1.5 1
1 0.5

f=exp(-(X.^2+Y.^2));surf(X,Y,f)
0
0.5 -0.5
0 -1

73

Use the colormap for the palette


Color palette
colorbar
Associate a legend to the color palette: example
colormap(gray)
x=[-1:0.1:1];
y=[0:0.1:2];
[X,Y]=meshgrid(x,y);
f=exp(-(X.^2+Y.^2));surf(X,Y,f)
colorbar
Further example
colormap(gray)
x=[-1:0.1:1];
y=[0:0.1:2];
[X,Y]=meshgrid(x,y);
f=log((X.^2+Y.^2)+1);
surf(X,Y,f)
colorbar

76
Restrictions to a vertical plot
Not for all the x, but only for a specific value of x. Unfortunately, we
cannot just use 1 value, but we need to replicate the value as many times
as the length of the vector of y:

Example: draw the surface only for x=-1:


y = [-2:0.1:2];
x=-1*ones(size(y)); 0.4

[X,Y] = meshgrid (x,y); 0.3

f = exp(-X.^2-Y.^2); 0.2

surf(X,Y,f) 0.1

0
2
1 0
0 -0.5
-1
-1 -1.5
-2 -2

The assignment of x is all that changes; all the rest is as before.


One can decide to keep the original x and restrict the y. In this case the
roles just exchange: x=[-1:0.1:1]; y=-1*ones(size(x));
All the rest remains the same.
Further exercises
Draw the functions

f(x,y)=x^2-y^2; with grey


tones
f(x,y)=x^2-x; with contours
f(x,y)=exp(x+y); with colors
f(x,y)=log(x+y+1); with
colors and colorbar
Solutions
x=[-1:0.1:1];y=[0:0.1:3];f=X.^2-
Y.^2;surf(X,Y,f);colormap(gray)
x=[-1:0.1:1];y=[0:0.1:3];f=X.^2-X; surfc(X,Y,f);
X=[-1:0.1:1];y=[-1:0.1:2];f=exp(X+Y);
surf(X,Y,f);colormap(hsv)
X=[-1:0.1:1];y=[-1:0.1:2];f=log(X+Y+1);
surf(X,Y,f);colormap(jet)

You might also like