Macroeconomic Policy: A Short Matlab Tutorial: Mario Alloza October 27, 2015
Macroeconomic Policy: A Short Matlab Tutorial: Mario Alloza October 27, 2015
Mario Alloza∗
Contents 1 Introduction
1 Introduction 1 Matlab is a programming language that allows a wide
variety of numerical computations and is particularly
2 Basic Commands 2 powerful when performing matrices manipulations.
2.1 Algebraic Operations . . . . . . . . . . 2 The user’s interface includes the following windows
2.2 Matrices . . . . . . . . . . . . . . . . . 2 (see Figure 1):
2.3 Useful Built-in Functions . . . . . . . 3
Commmand Window (highlighted in red in Fig-
3 Loading and Saving 4
ure 1): this space has a double function: (i) al-
3.1 Importing Data . . . . . . . . . . . . . 4
lows the user to type in any input (commands
3.2 Exporting Data . . . . . . . . . . . . . 5
with instructions) and (ii) shows the output of
3.3 Loading and saving matrices . . . . . . 5
any requested operation.
4 Plots 5
Workspace (highlighted in green): here is where
5 Loops 6 all created objects are stored. They can be
5.1 The “for” Loop . . . . . . . . . . . . . 6 accessed by double-click in their icons, or typ-
5.2 The “while” Loop. . . . . . . . . . . . 7 ing open name of the object in the Command
Window. In both cases an Excel-like spread-
6 Functions 7 sheet (the Variable Editor Window) will pop up
listing the values of the object.
7 Debugging, Efficient Computation and
Good Practices 8 Current Folder (highlighted in yellow): shows
the files contained in the current folder. The
8 Learning Matlab 9
current path is also shown in the box highlighted
in purple in Figure 1; it can be changed it to any
other folder.
1
be our starting point when creating a new pro- 2.2 Matrices
gram. The code written in the Editor can be run
Constructing Matrices A matrix can be defined
by pressing the F5 key or clicking on the green
in Matlab by typing one by one its elements sep-
triangle icon.
arating the columns by a comma (or a space) and
jumping to the next row using a semicolon (or by hit-
ting enter). Matrices are always enclosed by square
Figure 1: Matlab User’s Interface brackets []. Then, we have:
X = [3,7;1,4]
Z = [3 7
1 4]
X'
M = [X Z']
2 Basic Commands
N = [X [3;4] ]
2
A, with elements Ai,j = Xi,j · Yi,j , where i indexes a model with constant: if we have T observations in
the rows, and j indexes the columns. a matrix X, we can write X = [ones(T,1) X].
1:6
We can access a group of elements by using the
(1:6)'
symbol :. Hence, Q(1:4,3) selects the elements from 0:2:10
the 1st to the 4th row in the 3rd column of matrix Q.
If we just write Q(:,3), all the elements of the 3rd Similarly, the command linespace(x1,x2,n) will
row will be selected. In our example: create a row vector of n equally separated numbers
from x1 to x2.
X(1:2,1) = 3
X(:,2) = Y(:,2) linspace(1,10,10)'
3
Note that there exist lots of built-in function in X = [3,7;1,4]
Matlab as mean, min, max, sum, round, . . . Use the kron(ones(2,2),X)
repmat(X,2,2)
help command to see how they work.
We can also vectorise a matrix in Matlab. Hence, a
Time-Series Functions. When dealing with n×m matrix would be converted into a nm×1 vector,
time-series data, latest versions of Matlab include by stacking all the columns of the matrix. Inversely,
commands such as lagmatrix(Y, n), which creates the command reshape(X,n,m) can change the shape
a new matrix as Y, but lagged n periods. Note that of a matrix X to a new one with n rows and m columns.
when estimating a time-series model, you may want
to include a number of lags, then you can substi-
tute n by a sequence of lags as 1:n. The command vecX = X(:)
reshape(vecX,2,2)
diff(Y,n) will compute the n-th difference of matrix
Y. Examples: We can determine the size of a matrix by means
of the command size(). This particular instruction,
R = [4 7; 5 8; 9 3; 12 0; 1 5]; as many other functions implemented in Matlab, de-
lagmatrix(R,1:3) livers two different objects as output: an object con-
diff(R,1) taining the number of rows, and an object containing
the number of columns. Therefore, we have to define
Random Number Generators. Sometimes, we the output (what is at the left hand side of the =
may be interested in generating random numbers. symbol) accordingly:
This functionality is implemented in Matlab by using
the commands rand(m,n) or randn(m,n) to gener- [rows columns] = size(X)
ate m × n matrices of random numbers following a
uniform or a N (0, 1) distribution, respectively. Tip: the command length(X) can alternatively
be used to compute the maximum size of matrix X
(i.e. in a n × m matrix, it returns n if n > m or m
rand
otherwise).
rand(10,2)
randn(5)
4
When we want to import data in other format
X = (1:100)';
rather than a spreadsheet, or when we are using a
Y1 = sin(X)
Mac (we cannot use the above command with com- Y2 = cos(X)+2
puters that do not use Microsoft Windows as opera- plot(X,Y1)
tive system) we can use the command importdata:
When running a code/program that plots multi-
ple pictures, keep in mind that by default Matlab
data imp = importdata('GDPdata.csv'); will make the plots in the same window, overwrit-
mydata = data imp.data;
ing the previous figure. To make things clear, you
TIME = mydata(:,1);
GDP = mydata(:,2); can either use the command close all to close the
previous file or use the command figure before the
In this example we have used a comma-separated code regarding the plot to ask Matlab to draw the
(.csv) file, but we could have alternatively used new picture on a separate window. These windows
other types of text files. Notice that, when we use can be numbered: figure(1), figure(2) . . .
the command importdata, the object that is created
(data imp in the above example) is what Matlab calls
figure
a “structure”, which includes both data and text. plot(X,[Y1 Y2])
The second line in the above code extracts just the
data component of this structure. Matlab implements a wide range of plot types, a
feature which may be useful depending on the nature
3.2 Exporting Data of the data we want to plot:
5
Wn,m in row n and column m as Wn,m = nm . There-
Figure 2: An Example of Plotting Options in Matlab
fore, we use two nested for loops to “scan” each
Different Logarithmic Functions element in the matrix W and compute the operation
10
log(x)
log(x)+3
(we would have used three loops for a 3-dimensional
9
8
log(x)+1
matrix):
7
logarithmic function
6
W = zeros(5,4)
5 [rows columns] = size(W)
4 for m=1:columns
3 for n=1:rows
2
W(n,m) = n.ˆm
end
1
end
0
0 5 10 15 20 25 30 35 40 45
X
y = zeros(100,1);
5 Loops eps = randn(100,1);
for i=2:100
When the same instruction is required to be repeated y(i,1) = y(i-1,1) + eps(i,1),
a number of times, we may use a loop to ask Matlab end
plot(y)
to execute this repeated instruction. The use of loops
is very common in programming, and can enormously
simplify one’s code.
A Simple “for” Loop with Conditional State-
ments. We often want to compute an instruction
5.1 The “for” Loop conditional to some statement. In this situation, we
A Simple “for” Loop. The for loop repeats can use the command if condition to be checked
the same instruction as many times as we de- followed by the instruction and the command end.
fine. The syntax is very simple: the instruc- Additionally, we can add the command else to de-
tion to be repeated is preceded by the command fine a new operation to be executed if the condition is
for index=first iteration:last iteration and not met (Note: we could even add further conditions
is followed by end. For example: by using the command elseif):
6
5.2 The “while” Loop. When using our own function, it is important to
notice the following:
This loop, will execute the instruction for an unde-
fined number of times until some condition is met. The function name specified above, must be the
The syntax is very similar to the for loop. You same name that we used to save the new .m file:
should keep in mind to observations when using this if our function is called ComputeStdErrors, the
kind of loops. First, before the loop finishes (i.e. be- new file containing the function will be saved as
fore writing end), we have to write an instruction ComputeStdErrors.m.
to tell Matlab that the loop must be kept running
We can call the function form our main file
before the condition is not met. Second, the while
by writing [result 1, result 2 ...] =
loop can be running an infinite number of times if the
function name(argument 1, argument 2...).
condition is not met; if this is due to a programming
Note that we write result and argument
error you must stop Matlab with Ctrl+C.
instead of output and input to emphasise that
the names give to these variables don’t need to
draw = rand be the same.
while draw <0.9
display('The draw was below 0.9, try again.') To illustrate the use of functions, the next exam-
draw = rand ple creates artificial data and runs an OLS estima-
end
tion of the classical linear model by means of a func-
tion defined by our own function, called OLSestim.
This example is also meant to summarise some of the
6 Functions highlighted concepts shown in this short tutorial.The
main file is:
Commands such as mean() or rand() call built-in
functions already incorporated in Matlab. However,
we can create our own functions to perform some % OLS estimation of artificially generated data
specific tasks. In this way, we will simplify our code
% We assume we know the true DGP
both because we don’t have to replicate code (instead T = 50000; % number of observations
of writing the same set of instructions twice, we can eps = randn(T,1)*7; % errors
just call our function) and because our program will X = randn(T,1)*2 + 3; % regressors
X = [ones(T,1) X]; %include a constant
be more readable when having fewer lines in the main
beta true = [0.7 1.2]'; % true parameter
file, creating separated files with functions to execute Y = X*beta true + eps;
specific tasks.
When writing a function we will use the following % Run the estimation
syntax: [beta estim,sigma estim] = OLSestim(X,Y);
1. begin the file with function [output 1, display('The true parameters are:');
beta true
output 2 ...] = function name(input 1, display('The estimated parameters are:');
input 2...) beta estim
2. write all the instructions that making use of % Repeat the estimation B times
input 1, input 2... specified by the user will % for different draws of epsilon
produce output 1, output 2 .... Obviously, B = 1000;
beta mat = zeros(B,2);
we must use the same names to define the out-
for i=1:B
put variables as we defined them in the previous eps = randn(T,1)*7;
point. Y = X*beta true + eps;
[beta mat(i,:), sigma mat(i,:)] = OLSestim(X,Y);
3. end the function file with the command end. end
7
Try to use functions to separate from the main
display('Mean estimation of the slope coeff.:') code those tasks that are to be repeated a num-
mean(beta mat(:,2))
ber of times or that contain specific code which
hist(beta mat(:,2),50)
can be easily isolated front the core of our pro-
gram. Ideally, a Matlab project will involve a
bunch of programs/functions which are called
Figure 3: Distribution of the Slope Estimator over
from a “master” m-file.
Different Samples
Be generous writing comments (using the sym-
700
bol %). Despite that is a tedious thing to do
600 when writing code, it will prove to be a very use-
500
ful practice when you come back to your projects
after some time.
400
for you.
100
0
Keep it smart. There are many ways to deal
1.15 1.2 1.25
with the same task, however, more elegant ways
tend to make your code more understandable
by others and even by your own (e.g. copy and
The m-file containing the function OLSestim is: paste several times the some code lines can be
substituted by a loop).
function [beta hat,sigma hat] = OLSestim(XX,YY)
Efficient Computation. Among other features of
beta hat = inv(XX'*XX)*XX'*YY; your computer, Matlab performance is strongly
correlated with your computer processor. How-
% Alternatively, a more efficient code would be:
ever, programs can run much faster when we
% beta estimt = X\Y;
avoid tasks that are particularly slow for Mat-
residuals = YY - XX*beta hat; lab:
df = length(XX)-length(beta hat);
sigma sq = (residuals'*residuals)/df; – Matlab loves matrices: when possible, use
sigma hat = sqrt(sigma sq);
matrix operations rather than loops. Ex-
end ample: using a loop to execute the same in-
struction for each element of a matrix may
be slower than doing once the instruction
for the whole matrix.
7 Debugging, Efficient Computa-
– When running a loop that stores the results
tion and Good Practices in a matrix, it is faster to define this con-
taining only zeros before the loop starts,
Unfortunately, our own programs will not always run
rather than letting the size of the matrix
smoothly and some programming mistakes must be
growing in each iteration.
detected. Despite Matlab offers some tools to make
this task less painful, writing “clean” and fast code, – Some commands are faster than others
can save us hours (or even days!). Here there are while producing the same results: Y/X is
some tips: faster than X*inv(Y).
8
– To check the time that Matlab takes to per- example, there is no need to program a Choleski de-
form an operation you can use tic and toc composition when the command chol() already does
as in tic; randn(10000,1); toc. this.
One of the greatest advantage of Matlab is that is
Take advantage of Matlab capabilities. You can
a widely used software. That means that there ex-
divide your code in cells (see the Matlab menu
ist a lot of code already written. Some economists
called “Cells”) by writing two comment symbols
share freely their code what makes learning much
%% for each cell. Matlab allows you to evaluate
easier: visit for example the webpages of Chris Sims,
these cells instead of the whole program, some-
Larry Christiano or Martı́n Uribe for some examples.
thing that may be useful at the early stages of
Some journals as the Review of Economic Dynamics
your project.
or some articles of American Economic Review in-
When debugging, it is sometimes very conve- clude code replicating the results of the published
nient to check that Matlab is doing what you papers; that’s a perfect opportunity to see how a
think it should be doing. Setting breakpoints professional code looks like.
(see Matlab menu “Debugging” or click at the
right of a line number in for code until a red ball
appears) while make Matlab execute all the code
until this point and allow you to progress step
by step from that point onwards. This is partic-
ularly interesting when running a code that in-
volves functions, since when Matlab is executing
a function, the objects created by this functions
are not stored unless they are defined as output.
8 Learning Matlab
Matlab implements a wide variety of functions. Since
remembering all the bells and whistles of each one is a
hard thing to do, Matlab incorporates a detailed doc-
umentation of each command. You can access to this
information by writing help unknown command. Ad-
ditionally, use the “Help” menu to browse and search
all the functions implemented to check if Matlab al-
ready incorporates what you are looking for. For