0% found this document useful (0 votes)
36 views

Macroeconomic Policy: A Short Matlab Tutorial: Mario Alloza October 27, 2015

This document provides an introduction to using Matlab for macroeconomic policy analysis. It describes Matlab's user interface including the command window, workspace, current folder, and editor. It also outlines basic commands for algebraic operations, matrices, loading and saving data, plots, loops, and functions. The document serves as a short tutorial for getting started with Matlab.

Uploaded by

kashmira
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Macroeconomic Policy: A Short Matlab Tutorial: Mario Alloza October 27, 2015

This document provides an introduction to using Matlab for macroeconomic policy analysis. It describes Matlab's user interface including the command window, workspace, current folder, and editor. It also outlines basic commands for algebraic operations, matrices, loading and saving data, plots, loops, and functions. The document serves as a short tutorial for getting started with Matlab.

Uploaded by

kashmira
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Macroeconomic Policy: A Short Matlab Tutorial

Mario Alloza∗

October 27, 2015

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.

ˆ Command History (not shown): keeps a record


of all the commands used.

ˆ Editor (highlighted in blue): in most cases, in-


stead of using the Command Window to type in
the instructions, we may prefer to create a file
containing a series of commands or a program
created by our own. We use the Editor to create

PhD candidate, Department of Economics, UCL. E-mail: this files (with the extension .m appended at the
[email protected] end of the filename). These m-files will usually

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]

Where X = Z, or X - Z is the null matrix.


We can transpose a matrix (switching rows by
columns) by appending the symbol ’ after a matrix,
as in:

X'

We can create new matrices by merging two or


more matrices, or appending vectors or scalars:

M = [X Z']
2 Basic Commands
N = [X [3;4] ]

2.1 Algebraic Operations


To perform basic operations with scalars, we can type Matrices Operations. As in the case with scalar
them directly in the Command Window and the out- operations, we can perform algebraic operations with
put will be shown immediately after our command, matrices:
as in a calculator; e.g.:
Y = [4 9; 12 0]
X * Y
5+7
20*3
3/5 To invert a matrix, we can either use the command
ansˆ2 inv() or, more accurately, the “division” operator.
Keep always in mind that matrix multiplication or
Matlab will store the results of these operations in division are not commutative, i.e. the order does
an object called ans which will be overwritten each matter.
time we type a command. Alternatively, we can de-
fine a name for the result of an operation, e.g.:
inv(Z)
X * inv(Z)
myresult = 5+7 X / Z
X = 13-11
Y = 4ˆX We may be interested in computing the Hadamard
product (dot product) between two matrices of the
Note that Matlab is case-sensitive, so X 6= x. same dimensions. We then obtain a new matrix, say

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].

X .* Y 2.3 Useful Built-in Functions


X ./ Y
A list with some convenient commands:
Tip: Now we can solve system of matrices with
the tools we have used so far. Rearrange the system Housekeeping. clear cleans all the objects de-
to have the form: A ∗ B = C where A are the coef- fined during the work-session. clc cleans all the
ficients, B the unknowns and C real numbers. We commands (and their output) typed in the Command
can solve for the unknowns by typing: B=inv(A)*C . Window. close all closes all the opened windows
showing figures.
Accessing to Elements of a Matrix. We can
access to the elements of a matrix, to edit them, or Vectors. We can create vectors of consecutive
to create a new variable from them. We select an numbers by using the symbol :. If we write n:m,
element of a matrix by writing the number of row Matlab will produce a row vector containing a list
and column (in brackets) just after the name of the of numbers n, n + 1, n + 2, . . . , m − 2, m − 1, m. We
matrix: can create a column vector by transposing the row
vector. Additionally, we can create a list of num-
bers n, n + k, n + 2k, . . . , m − 2k, m − k, m with the
element 1 2 = X(1,2)
X(1,2) = 654 command n:k:m:
X(end,2) = 7

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)'

Tip: any of the above commands, can be used to


Some Special Matrices. Here we list some com- incorporate an extra column (or row) to a matrix of
mands regarding interesting matrices such as the regressors containing a linear trend. How could we
identity matrix, or matrices containing always the add a quadratic trend to a matrix?
same element:
Elementary Functions. Commands as sqrt(),
eye(3) % a 3x3 diagonal matrix std(), exp() or log() compute the square root, the
X*eye(2) % returns matrix X standard deviation, the exponential or the logarithm
5 * eye(3) % a 3x3 diagonal matrix with 5s of the argument inside the brackets:
zeros(3) % a 3x3 matrix of zeros
ones(4) % a 4x4 matrix of ones
diag(X) % vector with the diagonal elements sqrt(144)
std(1:6)
Tip: a vector of ones can be easily added to an ex- exp(1)
isting matrix of regressors when we want to estimate log(exp(1))

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)

Tip: What if we want to draw numbers from 3 Loading and Saving


a N (µ, σ) distribution? We could implement this
3.1 Importing Data
(assuming, for example µ = 5 and σ = 2 using
data=randn(10000,2)*2 + 5;. To check it, write Matlab can load data in excel format (.xls or .xlsx
mean(data) and std(data). extensions) by using the command xlsread. We will
have to specify first the name of the file (including
Changing the Shape of Matrices. If we are in- its extension) and the sheet where the data is place
terested in replicating the same matrix a number of (if there is only one sheet, you can skip this step).
times, we can make use of the Kronecker product Both arguments should be enclosed in ’’:
function built in Matlab. Recall that A ⊗ B multi-
plies each element of matrix A by the whole matrix
mydata = xlsread('GDPdata.xls','dataMatlab');
B, therefore, if we substitute A by a matrix of ones of TIME = mydata(:,1);
order n, we would be replicating matrix B n times. GDP = mydata(:,2);
The same can be achieved by using the command
repmat: It is important to note that our Current Folder (see
section 1) must be the one that contains the file that
we are trying to load.

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:

The easiest way to export data is to open the Variable


close all
Editor Window (see the description of the Workspace
a= randn(1000,1);
in section 1) and then copy the values and paste them hist(a)
into Excel (or elsewhere). This can be done in a
more elegant way by using the commands xlswrite You can manipulate the options of a plot: font,
or export size, colours, etc. Here we show an example of plot
using some of the available features, which can be
3.3 Loading and saving matrices appreciated in Figure 2

The commands load and save allow us to create or


open a file containing all or some of the matrices in figure
plot(log(1:50),'--k','LineWidth',2)
our Workspace. The resulting file will be readable hold on;
only by Matlab. This could be a potential solution plot(log(1:50)+3,'-ro','MarkerEdgeColor','k', ...
when using very large matrices that use up the com- 'MarkerFaceColor','g')
puter’s memory; in that case, by dividing a big ma- plot(log(1:50)+1,'-b','MarkerEdgeColor','k', ...
'LineWidth',4)
trix in smaller ones that will be saved and loaded title('Different Logarithmic Functions')
sequentially, we would be able to perform certain op- legend('log(x)','log(x)+3','log(x)+1')
erations in a faster way. xlabel('X')
ylabel('logarithmic function')
axis([0 45 0 10])
4 Plots
Matlab is a particularly suitable tool to plot data. Saving Plots. You can save any plot that you have
The basic command for plotting a vector is plot(Y). computed: in the figure window, click on File and
However, we can also type plot(X,Y) to plot data in then on Save As. You will be able to store the graph
vector Y on vector X: in a wide variety of formats: pdf, eps, png, jpg. . .

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

Example: generating a Random Walk. Arti-


ficial time-series data (or any operation requiring a
You can also use the format fig, the extension for
recursive computation) can be generated using a for
Matlab figures, that will allow you to reopen the
loop. In this example we generate the following time
saved figure in Matlab and perform operations with
series: yt = yt−1 + εt , where εt ∼ N (0, 1) and y0 = 0.
it (e.g.: change the appearance of the figure).

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):

for n=1:3 P = [rand(20,1) zeros(20,1)];


n for i = 1:length(P)
end if P(i,1) ≥ 0.5
P(i,2) = 100;
else
P(i,2) = -2;
Nested Loops. We can nest two ore more for end
loops to execute different operations. In the follow- end
ing example, we are defining each element of matrix

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

300 ˆ Keep it simple. Avoid complex names for new


variables and try to find a method that works
200

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.

ˆ You can also compare that two alternative pro-


cedures yield the same results by using con-
ditional statements: true statements as 3==3
will return 1 as an answer, while false state-
ments as 3==5 will return 0 as an answer.
If you want to compare two vector of re-
sults that seem to have similar results but you
cannot check it due to its large dimension,
min(my result 1==my result 2) should be 1,
otherwise, the two methods are not equivalent
for some cases.

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

You might also like