Introduction To Matlab: Quantitative Macroeconomics
Introduction To Matlab: Quantitative Macroeconomics
Introduction to Matlab
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
Useful resources :
Mathworks documentations : http://mathworks.com/help/matlab/
Kevin Sheppard : Matlab Notes
Matlab desktop
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.
To section your code, start the line with %% and the section name.
Matlab script
Creating variables
A scalar :
a=1
11 a=1
>> a=1
a =
1
A vector :
1
v = 2
3
Creating variables
A matrix :
1 2 3
A= 4 5 6
7 8 9
Special matrices
Matrices of zeros
0 0 ··· 0 0
X10×10 = 0 0 ··· Y10×2 = 0 0
.. .. . . .. ..
. . . . .
Matrices of ones
1 1 ···
Z20×20 = 1 1 ···
.. .. . .
. . .
Special matrices
Identity matrices
1 0 ···
I = 0 1 ···
.. .. . .
. . .
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
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
Example
1 Compute a matrix of the form :
1 0
X = 2 4
2 5
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
+ Addition * Multiplication
- Subtraction / Division
Matrix algebra :
For matrices :
Logical statements
== Equal
∼= Not equal
> Bigger
>= Bigger or equal
< Smaller
<= Smaller or equal
& Logical “and”
| Logical “or”
Example
Let A and B be two matrices :
4 3 1 2
A= , B=
2 1 3 4
X =A·B
Random Variables1
You can generate random variables using Matlab :
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
while statements
while condition
statements
end
for loops
for index=values
statements
end
xt = ρ · xt−1 + t
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.
Import wizard
You can save the variables that are in your workspace in a .mat file :
MyData = save('filename','variable1','variable2',...)
Graphs
Line plots
Scatter plots
Histogramms
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.
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
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')
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.
-1
-2
-3
-4
-5
0 1 2 3 4 5 6 7 8 9 10
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
Histogram
Syntax : histogram(X,n)
histogram creates a histogram plot of X
n determines the number of bins.
140
120
100
80
60
40
20
0
-4 -3 -2 -1 0 1 2 3 4
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
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
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
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
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.
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')
Functions
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
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
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
min =
0.5000
% alternatively :
min = fminsearch(@(x) x.^2-x-6,x0) %write it directly
min = fminsearch(@(x) MyFunction(x)*1,x0) %transform it
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
y = −x 2 + x + 4
Example
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