0% found this document useful (0 votes)
123 views52 pages

Introduction To Matlab: Quantitative Macroeconomics

This document provides an introduction to using MATLAB for quantitative macroeconomics. It discusses basics like creating variables, matrices, operations on matrices using indexing and aggregation, data manipulation through replication and replacement of elements. Special matrices like zeros, ones and identity matrices are also introduced.

Uploaded by

Amil Musovic
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)
123 views52 pages

Introduction To Matlab: Quantitative Macroeconomics

This document provides an introduction to using MATLAB for quantitative macroeconomics. It discusses basics like creating variables, matrices, operations on matrices using indexing and aggregation, data manipulation through replication and replacement of elements. Special matrices like zeros, ones and identity matrices are also introduced.

Uploaded by

Amil Musovic
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/ 52

Quantitative Macroeconomics

Introduction to Matlab

Seda Basihos Andreas Tischbirek

Department of Economics
HEC Lausanne

28 September 2020
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Introduction
Matlab is a very powerful software allowing matrix manipulations, plotting
of functions and data, algorithms, etc.

MAT
| {z } LAB
|{z}
Matrix Laboratory

Your best friends are :


Google
“help” button (hit F1)

Useful resources :
Mathworks documentations : http://mathworks.com/help/matlab/
Kevin Sheppard : Matlab Notes

Special thanks to Frederic Martenet for his work on a previous version of


these slides.
UNIL-HEC Introduction to Matlab 28 September 2020
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Matlab desktop

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Matlab script

Always use a script to store your commands (remember the Stata do-files).
A .m file is created.
Make sure it is in the current folder.

Begin by clearing the workspace :


1 %% Clear the Workspace
2 clc % clear the command window
3 close all % close all open graphs
4 clear all % clear the workspace

To comment your code, use %

To section your code, start the line with %% and the section name.

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Matlab script

To run some code : highlight and hit F7


To run the current section : hit “Run Section”
To run the current section and jump to the next : hit “Run and Advance”
UNIL-HEC Introduction to Matlab 28 September 2020
1. Basic Input
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Creating variables
A scalar :
a=1
11 a=1

>> a=1
a =
1

Note : add ; at the end to show no output on the command window


12 a=1; % add ; at the end for no output

A vector : 
1
v = 2 
3

13 v=[1;2;3]; % separate the elements with ;

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Creating variables

A matrix :  
1 2 3
A= 4 5 6 
7 8 9

14 A=[1 2 3;4 5 6;7 8 9]; % separate the lines with ;

Don’t call variables the same names as functions !

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Special matrices
Matrices of zeros
   
0 0 ··· 0 0
X10×10 =  0 0 ···  Y10×2 = 0 0 
   
.. .. . . .. ..
. . . . .

16 X=zeros(10); % a 10x10 matrix on zeros

17 Y=zeros(10,2); % a 10x2 matrix of zeros

Matrices of ones
 
1 1 ···
Z20×20 =  1 1 ··· 
 
.. .. . .
. . .

18 Z=ones(20); % a 20x20 matrix of ones

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Special matrices
Identity matrices
 
1 0 ···
I =  0 1 ··· 
 
.. .. . .
. . .

19 I=eye(15); % 15x15 identity matrix

To know the dimensions of a matrix :


21 size(Y)
22 [n,m]=size(Y); % to store the dimensions

Or check the workspace :

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Data manipulation
   
1 2 3 1 1 1
A= B=
4 5 6 2 2 2
Indexing :
A(2,1) : the element in the second line and first column A2,1 = 4
 
2
A(:,2) : the second column col2 (A) =  
5
 

A(2,end-1:end) : the last two elements of the column


 2

row2 (A) = 5 6
last two
Aggregation :
 
 1 2 3 1 1 1
[A B] : concatenate two matrices A B =
4 5 6 2 2 2
 
  1 2 3
A  4 5 6 
[A; B] : append two matrices = 
B  1 1 1 
2 2 2
UNIL-HEC Introduction to Matlab 28 September 2020
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Data manipulation
   
1 2 3 1 1 1
A= B=
4 5 6 2 2 2
Replicate a matrix :
 
A A A
repmat(A,2,3) : replicate the matrix A 2 × 3 times
A A A
Replace elements :
 
1 2 3
A(2,1)=0 : replace a single element A=
0 5 6
 
1 1 1
B(2,:)=[0 0 0] : replace a whole row B=
0 0 0
 
1 0 1
B(:,2)=[0; 0] : replace a whole colomn B=
2 0 2
Delete elements :

B(2,:)=[ ] : delete a row B= 1 1 1
 
1 2
A(:,3)=[ ] : delete a colomn A=
4 5

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Example
1 Compute a matrix of the form :
 
1 0
X = 2 4 
2 5

2 Add a column of ones :


 
1 1 0
X = 1 2 4 
1 2 5

3 Delete the third row of the matrix :


 
1 1 0
X =
1 2 4

4 Compute the size of this matrix and store it as n for rows and m for
columns :
n=2 m=3
UNIL-HEC Introduction to Matlab 28 September 2020
2. Operations
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Simple operations : algebra


Algebraic operations are as expected :

+ Addition * Multiplication
- Subtraction / Division

Matrix algebra :

2*A Scalar multiplication 2·A


1
A/4 Scalar division 4 ·A
A+B Vector/matrix addition A+B
A-B Vector/matrix subtraction A−B
A^2 Matrix squaring A · A = A2
A' Matrix transposing A0 = AT
A*B Matrix multiplication A·B
A/B Matrix right division A · B −1
A\B Matrix left division A−1 · B
A.^2 Element-wise squaring
A.*B Element-wise multiplication
A./B Element-wise division
Note : use “.” to perform element-wise operations.

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Simple operations: functions


Some functions have very intuitive names :

log(v) Element-wise natural logarithm


sum(v) Sum of vector elements
mean(v) Mean of vector elements
var(v) Variance of vector elements
std(v) Standard deviation of vector elements
max(v) Maximum
min(v) Minimum

For matrices :

mean(A,1) Mean of each column (= mean(A))


mean(A,2) Mean of each row
mean(A(:)) Mean of all elements
max(A(:)) Maximum of a matrix
det(A) Determinant
trace(A) Trace
inv(A) Inverse
eig(A) Vector of eigenvalues

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Logical statements

== Equal
∼= Not equal
> Bigger
>= Bigger or equal
< Smaller
<= Smaller or equal
& Logical “and”
| Logical “or”

The output of a logical statement is either :


0 if the statement is false.
1 if the statement if true.
   
1 2 3 0 0 0
Example : A = A>3 would yield
4 5 6 1 1 1
UNIL-HEC Introduction to Matlab 28 September 2020
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Example
Let A and B be two matrices :
   
4 3 1 2
A= , B=
2 1 3 4

1 Compute the element wise multiplication of A and B.


 
4·1 3·2
2·3 1·4

2 Compute the matrix X as the multiplication of A and B.

X =A·B

3 Compute the mean of all elments in X .

4 Compute the matrix C = (X 0 X )−1 .


UNIL-HEC Introduction to Matlab 28 September 2020
3. Random Variables
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Random Variables1
You can generate random variables using Matlab :

rand Random uniform [0 1]


randn Random standard normal
randi Random integer

26 %% Random variables
27 rand(3); % a 3x3 matrix of random uniform numbers
28
29 randn(10,1); % a 10x1 vector of random normal numbers
30
31 randi(100); % a random integer between 1 and 100
32
33 randi(100,10,1) % a 10x1 vector of random integers 1-100

1
Note that, as they are generated by the software, they are pseudorandom variables.
UNIL-HEC Introduction to Matlab 28 September 2020
4. Flow Control
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

if statements
An if statement executes a list of statements if the condition is true.
The syntax is :

if condition1
statement1
elseif condition2
statement2
else statement3
end

statement1 is executed if condition1 is true, and so on.


elseif should be used when, failed the first condition, there are other
conditions to meet. There can be more than one elseif .
else should be used when all conditions are false.
end is compulsory.
UNIL-HEC Introduction to Matlab 28 September 2020
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

while statements

A while statement is a collection of commands that is executed while the


condition is met :

while condition
statements
end

The statements must be enclosed by while and end.


The number of iterations is determined by condition.

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

for loops

A for statement is a collection of commands that is repeated for a specified


amount of times. The syntax is :

for index=values
statements
end

The statements must be enclosed by for and end.


The counter index varies with values. This defines the iterations of
the loop.
For example : t=1:100 for 100 iterations t=1,2,3,...,100

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Simulating an AR(1) process


Suppose we would like to simulate an AR(1) process of the form :
It can be used for labour income

xt = ρ · xt−1 + t

38 %% Loops : AR(1) process


39 rho=0.8; % Persistence degree
40 N=50; % Duration of the simulation
41 x=zeros(1,N); % x a vector of zeros
42 eps=zeros(1,N); % same for epsilon
43
44 eps(2)=0.1; % a shock occurs in period 2
45
46 % Simulation with a "for" loop
47 for t=2:N
48 x(t) = rho*x(t-1)+eps(t);
49 end

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Simulating an AR(1) process


We could specify different type of shocks using an if statement.

57 % set the type of shock you want


58 type=1;
59
60 if type==1
61 eps(1,2:N)=rand(1,N-1); % random uniform
62 elseif type==2
63 eps(1,2:N)=randn(1,N-1); % random standard normal
64 else
65 eps(2)=0.1; % shock of 0.1 at period 2 only
66 end;

Set the scalar type equal to :


1 for a random uniform
2 for a random standard normal
something else for a shock of 0.1 at period 2
UNIL-HEC Introduction to Matlab 28 September 2020
5. Working with Data
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Importing data
The most intuitive way to do it is to use the import wizard.
Hit the ‘Import Data” button.
Make sure the data files are in the current folder.

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Import wizard

1 Select your data file.


2 Select the options :
Select the data your want to import.
Chose variable names.
Import either a single matrix or one variable by column.
UNIL-HEC Introduction to Matlab 28 September 2020
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Importing data: commands

You can also use commands to import a file.

Import from a .xls spreadsheet :


MyData = xlsread('filename.xls','sheet','xlRange')
You can specify the sheet, ex : 'Sheet2'
and the range, ex : 'A1:C20'

Import from a Matlab .mat file :


MyData = load('filename.mat','variables')
You can specify the variables to import.
Note : it’s not necessary to assign variable names as they already exist.

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Saving a data set

You can save the variables that are in your workspace in a .mat file :

MyData = save('filename','variable1','variable2',...)

A file filename.mat is generated in the current folder.


You can choose which variables to include.

UNIL-HEC Introduction to Matlab 28 September 2020


6. Graphs
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Graphs

The three types of graph you will mostly use are :

Line plots

Scatter plots

Histogramms

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Plot
Syntax : plot(X,Y,LineSpec)
If X and Y are vectors, they must be of the same length. plot graphs
Y against X.
If X and Y are matrices, they must be of the same size. plot graphs
the columns of Y against the columns of X.
plot(Y) graphs the entries of Y against their position in the vector.
LineSpec are options that allow you to customize the plots.

Let’s use the following example :

74 %% Graphs : line plot


75 x = linspace(0,2*pi)'; % an linearly spaced vector
76 y1 = sin(x); % sinus of x
77 y2 = cos(x); % cosinus of x
78 Y = [y1 y2];

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7

80 figure(1) % assign a number


81 plot(x,Y) % line plot
82
83 figure(2)
84 plot(x,y1,x,y2)
85
86 figure(3)
87 plot(x,y1) % first plot
88 hold on % tell Matlab you want another one
89 plot(x,y2) % add a second plot
90 print -depsc sin_cos % export the graph as "sin_cos.eps"

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

You can change the line style, width, color, etc.


1

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7

92 figure(4)
93 plot(x,y1,'--','LineWidth',3)
94 hold on
95 plot(x,y2,':','color','black')

More options : Mathworks

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Scatter
Syntax : scatter(X,Y,S,C)
scatter creates a scatter plot with circles at the locations specified
by the vectors X and Y.
S determines the area of each market.
C determines the color of each market.

Let’s use the following example :


98 %% Graphs : scatter plot
99 x = linspace(0,3*pi,200);
100 y = cos(x) + randn(1,200);
4

-1

-2

-3

-4

-5
0 1 2 3 4 5 6 7 8 9 10

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

You can change the style, size, color, etc of the dots.
4

-1

-2

-3

-4

-5
0 1 2 3 4 5 6 7 8 9 10

103 s = linspace(1,100,length(x)); % create the size argument


104 c = linspace(1,100,length(x)); % create the color argument
105
106 figure(5)
107 scatter(x,y,s,c,'square','filled')

More options : Mathworks


UNIL-HEC Introduction to Matlab 28 September 2020
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Histogram
Syntax : histogram(X,n)
histogram creates a histogram plot of X
n determines the number of bins.

Let’s use the following example :

110 %% Graphs : histogram


111 x=randn(1000,1);

140

120

100

80

60

40

20

0
-4 -3 -2 -1 0 1 2 3 4

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

You can change the style, size, color, etc of the bars.
80

70

60

50

40

30

20

10

0
-4 -3 -2 -1 0 1 2 3 4

114 figure(6) number of bins


115 histogram(x,40,'FaceAlpha',0.2,'FaceColor','blue')

More options : Mathworks

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Options
For any type of graph, you may want to change its appearance.
To set the axis limits :
xlim( [xmin xmax] ) select values on the x-axes.
ylim( [ymin ymax] ) select values on the y-axes.
To label the axis :
xlabel('text') sets a label on the x-axis.
ylabel('text') sets a label on the y-axis.
To add a grid to the graph :
grid on adds major grid lines to the graph.
grid minor adds major and minor grid lines.
To add a title :
title('text','PropretyName','PropretyValue')
To add a legend :
legend('text')
UNIL-HEC Introduction to Matlab 28 September 2020
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Options
Options on
2
1
sin(x)
cos(x)

0.8 1.5

0.6
1

0.4
0.5

cos(x) & sin(x)


0.2

0
0

-0.2 -0.5

-0.4
-1

-0.6
-1.5

-0.8

-2
-1 0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 x

(a) Options off (b) Options on

124 plot(x,y1,'--','LineWidth',2)
125 hold on
126 plot(x,y2,'-.','color','black')
127 title('Options on','FontSize',18); legend('sin(x)','cos(x)')
128 ylabel('cos(x) & sin(x)');xlabel('x'); ylim([-2 2]);grid on
UNIL-HEC Introduction to Matlab 28 September 2020
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Subplot

Subplot allows you to create a figure combining several graphs.

Syntax : subplot(m,n,p)

subplot divides the current figure into an m-by-n grid and creates an
axes for a subplot in the position specified by p.

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

1
sin(x)

0.5

sin(x)
0

-0.5

-1
0 1 2 3 4 5 6 7
x

1
cos(x)

0.5
cos(x)

-0.5

-1
0 1 2 3 4 5 6 7
x

stands for the number of the plot so that we can change the option
133 subplot(2,1,1); % first plot
134 plot(x,y1,'--'); grid on;
135 ylabel('sin(x)'); legend('sin(x)'); xlabel('x');
136
137 subplot(2,1,2); % second plot
138 plot(x,y2,'-.','color','black'); grid on;
139 ylabel('cos(x)'); legend('cos(x)'); xlabel('x')

UNIL-HEC Introduction to Matlab 28 September 2020


7. Functions
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Functions

A function is a routine that reads a certain input and delivers a certain


output.

All functions must begin with a line of the form:

function [y1,y2,..,yN] = functionname(x1,x2,..,xM)

where x1, ..., xM are the inputs, y 1, ..., yN are the outputs and
functionname is the name of the function.
End the function with end
Save the script as a .m file called functionname.m in your working
directory.
You can then use it exactly like a standard Matlab function.
Functions can contain any operation you want

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Example
Suppose you want to write a function for

y = x2 − x − 6

1 function y = MyFunction(x)
2 % The function MyFunction returns the value y of
3 % the polynomial y = x^2 - x - 6
4 %
5 % x - input scalar or vector
6 % y - output scalar or vector
7
8 y = x.^2 - x - 6;
9 end

Try to add a description of your function.


The script must be saved as MyFunction.m in the working directory.

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Finding the roots

You can find the roots of a function using fsolve


Syntax : x = fsolve(@functionname,x0)
The algorithm starts at x0 and tries to solve the equation
functionname(x) = 0
To find multiple roots you should use several values in x0

For example, we can find the roots of MyFunction.m, which are the roots
of the polynomial y = x 2 − x − 6 :
x0 = [-4,4];
roots = fsolve(@MyFunction,x0)

roots =
-2.0000 3.0000

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Finding the minimum


You can find the minimum of a function using fminsearch
Syntax : x = fminsearch(@functionname,x0)
The algorithm starts at x0 and returns a value x that is a local
minimizer of the function

For example, we can find the minimum of MyFunction.m, which is the


minimum of the polynomial y = x 2 − x − 6 :
x0 = 0;
min = fminsearch(@MyFunction,x0)

min =
0.5000

% alternatively :
min = fminsearch(@(x) x.^2-x-6,x0) %write it directly
min = fminsearch(@(x) MyFunction(x)*1,x0) %transform it

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Finding the minimum


Be careful when guessing a value for x0
You may find a local minimum, but not the global minimum
You can guess visually using fplot(@functionname)
y

f (x)

x
x0

Local minimum
Global minimum
UNIL-HEC Introduction to Matlab 28 September 2020
Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Example

Find the maximum of the function

y = −x 2 + x + 4

UNIL-HEC Introduction to Matlab 28 September 2020


Introduction Basic Input Operations Random Variables Flow control Working with Data Graphs Functions

Example

Find the maximum of the function

y = −x 2 + x + 4

% Solution :
% code the function as "ExampleFunction.m"

Remember that :
n o n o
arg max f (x) = arg min − f (x)
x x

UNIL-HEC Introduction to Matlab 28 September 2020

You might also like