MATLAB Primer PDF
MATLAB Primer PDF
MATLAB Primer PDF
Stockholm University
Alex Schmitt
IIES
1
MATLAB Primer
1
Documentation
You can access the Matlab help documentation through the blue-white question mark icon in the top bar.
help command .
There are a number of free tutorials and other resources available online, e.g.
http://www.mathworks.com/help/techdoc/learn_matlab/bqr_2pl.html
http://www4.ncsu.edu/unity/users/p/pfackler/www/MPRIMER.htm
Further Readings:
On Fackler's
Basics
16
5
A=
9
4
44
matrix
3
10
6
15
2 13
11 8
7 12
14 1
is generated by typing:
B = [1 2 3 4]
For a
C = [1; 2; 3; 4]
A scalar is a
11
matrix:
D = 5
A;
[ ];
';' ends a row; within a row, ' ' indicates a new column.
C = [2; 3; 4; 5];
You can also assign a new value by using the old:
1 alex.schmitt@iies.su.se.
C = C - 1;
clear name
To empty your workspace, type
clear all.
A
Or, more complicated but nicer, with the
disp
command:
j th column of A.
A(i,j).
A(3,2)
For a vector it is enough to type
B(3)
A(:,1)
A(1:3,1)
A.
A.
A(1:3,1:3)
displays the matrix without the last row and the last column.
A([1 3],2)
To suppress output in your command window, end your command with a semicolon ';'.
Recall that
matrix addition
is only dened for matrices of the same dimension (same number of rows
and columns).
A + C
Recall that
rows in
B.
matrix multiplication
A * B
Piece-wise multiplication:
A .* C
This multiplies each element in
Piece-wise
operators:
C.
sum(diag(A))
max(A) (min(A))
max(A,[],2)
A'
inv(A)
A(:)
A.
A.
A.
vectorizes a matrix.
There are faster ways to create a matrix than typing it element by element. For example, a
matrix
Z = zeros(3,3);
... of zeros:
... of ones:
33
O = ones(3,3);
R = rand(3,3);
N = randn(3,3);
I = eye(3,3);
concatenating
other matrices.
above:
ZORN = [Z O; R N];
Creating the matrix works the same way as before, except that the elements are now matrices instead of
numbers. Note that this only works if the dimensions agree.
To check the
E = 1:10
F = 1:2:10
G = 100:-20:10
constructs a row vector with an increment of -20 from 100 down to 10.
H = linspace(1,5,10)
Instead of using the command window, it is much more convenient to write a program (
M-le)
that
diary
and comments.
Comments
can be added by starting a line with the percentage sign '%'. Use comments frequently in
A double percentage sign '%%' allows you to divide your M-le into sections that you can run separately
(instead of running the complete M-le). That's particularly useful with long and complicated M-les.
pause stops
the running of the program; it can be continued by hitting any key. That's useful if you want
To run your program hit the small Run icon on the toolbar (white document with blue arrow to the left
in old version, play button in the new version) or type the name of the le in the command window.
Note that the le that you want to run has to be in the current working directory (which is displayed in
the top bar) or in a directory on the Matlab
search path.
is not found in the current directory and oers to change to the right directory directly.
To add a directory to the Matlab search path, click on FileSet Path. If Matlab doesn't nd a program
in the current directory, it will search for it on all directories on the search path.
If you want to stop a running program before its end (for example if you have an algorithm that goes on
forever, due to lack of convergence), use the key combination
Crtl + C.
4.1
for-Loops
for-loop
following property:
Z = zeros(20,1);
for i = 1:19
Z(i+1) = Z(i) + 0.25;
end
, <=.
logical
They return a
matrix of the same size, with elements set to 1 where the relation is true and
- 1 > 2;
- eye(2) > zeros(2);
|| (or )
any(A):
A.
Note:
all(all(A))
logical 1 if
returns a logical 1 if
some elements in
isinteger(A):
isreal(A):
A.
all elements in
are nonzero.
returns a logical 1 if
returns a logical 1 if
all elements in
all elements in
A
4
all(A,2)
are integers.
any(any(A))
all(A,2)
returns a
4.4
while-Loops
A
while-loop
4.5
while-loop:
Z = zeros(20,1);
j = 1;
while j < 20
Z(j+1) = Z(j) + 0.25;
j = j + 1;
end
if-expressions
You can tell Matlab to execute a group of statements conditional on some logical expression. For example,
elseif
By using
if x > 0
and
&&
else,
isreal(x)
disp('x is positive.');
elseif x < 0
&&
isreal(x)
disp('x is negative.');
elseif x = 0
disp('x is zero.');
else
disp('x is not a real number.');
end
round(x)
ceil(x)
x.
floor(x)
x.
x.
Similarly,
a certain condition is no longer satised, and displays whatever message you specify.
If you are interested how long it takes for Matlab to execute an operation, you can switch on a stop watch
with
tic,
toc.
Functions
Functions are programs (M-les) that can accept input arguments and return output arguments. They
can be called from other programs in Matlab. Functions operate on variables within their
own workspace,
Data
und
size(Data,1)
and the number of rows as output argument. In addition to the already available functions,
A function has always the same structure. You must declare it to be a function and dene output, name
and input.
rows(A)
instead of
size(A,1) in order
rows(A):
function l = rows(x)
l = size(x,1);
Functions are also handy when you have an actual function (what you know as a function in Math)
that you want to evaluate at dierent values. For example, consider the function
y = min{e2x+2 , 20}.In
function y = fun1(x)
y = min(exp(2*x+2),20);
rows.m)
Some advice: store all your functions in one directory (e.g. 'Myfunctions') and add this directory to the
global variable can be retrieved from anywhere, in any program (script or function) in Matlab.
For example,
in the function
rows
be dierent variables.
mult.m
global x
in
x:
PROGRAM
...
global x;
x=1:10;
y=2;
z=mult(y);
...
FUNCTION
function a=mult(b);
global x;
a=x*b;
A function can have many inputs and many outputs. For example, consider
two inputs:
fun3
Note that if you call a function without storing the outputs in your workspace, it just returns the rst
output.
Some inputs can be optional. One way to implement this is to use the
nargin
other functions.
Plots
versus a vector
x.
For example,
x = 0:100;
y = 2 * x;
plot(x,y)
plot(x,y);
title('A linear function');
xlabel('x');
ylabel('y');
You can also have several graphs in one graph. In that case, the
legend
option is useful:
z = x.2;
plot(x,y,x,z);
legend('Linear function','Quadratic function')
subplot.
For example:
subplot(2,1,1); plot(x,y);
subplot(2,1,2); plot(x,z);
subplot(a,b,c) determine how the graphs are arranged. Think of the window
rows and b columns. The last argument c indicates the position of the graph
natural number, dierent for each subplot and a b).
figure.
In that way, you get output for all graphs in your program. Moreover, it
Another possibility is a histogram or barplot. For example, suppose you have a time series
frequency of each observation, type
x is distributed
- hist(x,-20:2.5:40);
of the intervals
where
x.
To plot the
hist(x,y),
- [N M] = hist(x,-20:2.5:40);
- N = N/size(EP,1);
- bar(M,N)
N,
0.3
Frequency, fraction
0.25
0.2
0.15
0.1
0.05
0
-30
-20
-10
10
Return
20
30
40
50
Suppose you want to plot a function with more than one argument. For example, let's plot the well-known
K = 1:10;
L = 0:0.1:1;
[x,y] = meshgrid(K,L);
z = x.alpha .* y.(1 - alpha);
meshgrid
figure
contour(x,y,z,n)
title('Cobb-Douglas production function')
xlabel('K')
ylabel('L')
zlabel('Y')
contour plot:
- figure
- mesh(x,y,z)
mesh plot:
Matlab oers a lot more plot types than the ones covered here, and a large number of options to modify
your graph. Check the documentation and play around with some commands, it's fun!
Strings
A string of characters is a block of text. Among other things, it is useful when you want to report results.
You can dene it like any other element in Matlab, with the dierence that strings must be set in single
quotation marks. For example,
- S = 'Matlab is fun!';
disp
command:
disp(S).
\n
%. .4f
Cell arrays
A cell array is a matrix of matrices. That is, it is a matrix, but instead of scalars, its elements can be
anything - for example matrices, vectors, etc.
{}.
- C = cell(2,2);
- C{1,1} = ones(4,3);
rows and
For example,
columns with
C = cell(m,n).
Elements can be
- C{1,2} = [1 2 3];
- C{2,1} = 'This element is string; the other ones are matrices.'
As a single string is treated as a vector, you cannot just dene a vector of strings, i.e. where each element
is a dierent string. Instead, you have to dene a cell array of strings:
S = {'mean','variance','standard deviation'};
10
quickly:
Numerical methods are a very important application in Matlab (and when using software in general). Examples
for basic methods are:
Numerical optimization
Function approximation
f (x).
f (x) is
Of course, we
could always try to nd the derivative analytically, and then use these. However, if
a complicated
wouldn't have to change your code if you want to use it on a dierent function.
The easiest way to approximate the rst derivative numerically is a two-point approximation, using two
function values:
f 0 (x)
f (x + ) f (x )
2
is a small number.
f 0 (x)
with a nite
dierence.
f 00 (x)
f (x + ) 2f (x) + f (x )
.
2
- fd = fdjac('fun5',10);
- fdd = fdhess('fun5',10);
10
fdjac
fdhess
(for the
10.2 Optimization
function . The simplest method is grid search: dene a grid (i.e. a vector
x the function
- x = -5:0.1:5; y = fun5(x);
- [ymax, ind] = max(y);
- xstar = x(ind);
to nd the at what
x)
f (x ):
max
command
Grid search has two major drawbacks: unless you have a good idea where the function attains its optimum,
you have to dene a very large grid, hence it can be time-consuming (especially if you have a multivariate
function). Moreover, it is not really accurate. However, it can be a good way to get an idea where
is
A more exact and often faster method is the Gradient (Newton-Raphson) method. It can be used for both
the univariate case (shown here) and the multivariate case.
As a starting point is, recall the rst-order Taylor approximation to an arbitrary function
(where
x0
should be close to
about
x0
x):
f:
We want to nd
x .
We know that at
x , f 0 (x ) = 0.
Hence,
x x0
We can use this for the following algorithm: start by guessing a value
x1 x0
f 0 (x0 )
.
f 00 (x0 )
x0
for
f 0 (x0 )
.
f 00 (x0 )
(1)
x1 6= x .
However,
hence should be a better guess. Thus, just repeat the step in (1) with
on:
x2 x1
In general, your
f 0 (x1 )
f 00 (x1 )
(n + 1)-th
guess is given by
xn+1 xn
f (xn )
f 00 (xn )
iterate
on (1), i.e. repeat the step several times, until you are close enough to
you stop if your updated guess is approximately the same as the previous one.
|xn+1 xn | <
where
= 1012 .
11
if
xn+1 xn .
x .
That is,
while-loop:
The rst line gives the stopping rule: the loop goes on as long as the variable
x0and
x x0.
fd
and
the new
I do it the
could also
x0
f 0 (x) = 0.
points close to
Note that there are a couple of potential problems with the Gradient method. First, we look for an
that
x0
x,
x such
x).
global maximum.
local
x .
In that case
might help.
Fortunately, you don't have to go through the procedure of programming the gradient method ourselves
whenever we have an optimization problem. Instead we can use some in-built Matlab commands.
fminsearch nds the minimum of a scalar function with several arguments, starting at an initial estimate
and using the gradient method.
fminbnd
guess.
gives you the minimum of the function - which (obviously) is not well-dened.
at the optimum.
Function optimization is an example of a more general type of problem: solving (a system of ) linear or
non-linear equations for their root(s).
Consider an equation
f (x) = y
or, equivalently,
f (x) y = 0.
equation.
12
In fact, that's what we have done when we maximized the function above using the gradient method: we
take rst derivatives, set them equal to zero and nd their roots.
Solving a system of linear equations is the most elementary problem that arises in computational economic
analysis. For example, consider the following simple system of equations:
x1 + x2 2x3 = 0
3x1 x3 = 5
2x1 x2 = 1
1
3
2
1
0
1
2
x1
0
1 x2 = 5
0
x3
1
(2)
Dene
1
A = 3
2
1
0
1
2
x1
0
1 , x = x2 , b = 5
0
x3
1
(x1 , x2 , x3 ),
Ax = b.
x, note that x = A1 b, A1
x in the following way:
- x = inv(A) * b;
To solve for
A.
and
b,
we
- x = A\b;
backslash operator:
Non-linear equations arise frequently in economic applications. To give you an easy example from macroeconomics, consider the simple consumption-saving problem
max U (c1 , c2 ) =
s
s.t.
c1
c1
1
+ 2
1
1
c1 = y s, c2 = y + (1 + r)s. ci denotes
r the (exogenous) interest rate.
consumption in period
i, s
saving,
income,
a discount
factor and
Plugging the constraints into the objective function and dierentiating w.r.t.
s,
optimality condition:
(y s) R(y + Rs) = 0.
This is an example of the so-called
We want to nd optimal saving, i.e. solve the Euler equation for
s.
makes this problem impossible to solve analytically (we could solve it for the special case if
= ).
There are a couple of dierent methods to solve this problem numerically, including Newton's method
which looks pretty similar to the Gradient method above - the Gradient method is actually just an
example of Newton's method applied on optimization problems. A simpler, but very reliable method for
the univariate case is the
Bisection method.
13
f (xn ) 0
0)
is
and
- a = -5; b = 1;
- while abs(fun(x)) > 10(-6)
if sign(fun(x)) == sign(fun(b))
b = x;
else
a = x;
end
x = (a+b)/2;
- end
sign
Note that if the root is not bracketed, there is no convergence and the algorithm will run forever. In that
case stop (Crtl
b.
- s = fzero('euler',s0);
Note that s0 species an initial
and
fminsearch:
which
guess.
If we want to solve a system of non-linear equations, bisection does not work. However, there are other
methods (in particular variations of Newton's method) that can be used in this case. The Matlab function
fsolve
We can actually use our savings problem from above as an example for this problem as well. Instead of
plugging in the budget constraints, we solve for the Euler equation in terms of consumption
the two constraints to one, getting rid of
the constraint - in two unknowns,
c0
and
s. Thus,
c1 :
c and combine
c
0 (1 + r)c1 = 0
y
c1
y
=0
c0 +
1+r
1+r
function z = euler2(c)
global mu gamma y r beta;
c0 = c(1); c1 = c(2);
z(1) = c0(-mu) - beta * (1+r) * c1(-gamma);
z(2) = c0 + c1 /(1+r) - y - y / (1+r);
euler,
c0
and
c1 .
The function's
output is also a vector with two elements, which are zero in optimum - only then the Euler equation and
the budget constraint hold simultaneously.
- c0 = ones(2,1);
- c = fsolve('euler2',c0);
and use
14
fsolve:
11
12
Problems
1. Write a program (M-le) that calculates the sum of all numbers between 1 and 100 (or, more generally,
between two integers
and
b).
20 1 column vector which starts with 0 and
aj+1 = aj + 0.25, where aj is the j th element of the vector.
whose elements
replace this matrix with one containing the natural logarithm of each element; 5) multiply this matrix with
the identity matrix; 6) replace this matrix with one containing the exponential function of each element;
7) replace this matrix with one containing the square root of each element; 8) multiply this matrix with
B.
What matrix do you expect to get? And why don't you get it?
4. Write a program that plots the following functions over a reasonable range of values:
y=e
y = log(x), y =
y = x2 , y = x3 ,
x.
intneighbours
that takes a scalar (a real number) as input and returns the two
natural numbers nearest to that number (excluding the number itself, in case it is a natural number). For
example,
intneighbours(0.5) = [0; 1]
intneighbours(-7) = [-8; -6]
6. Write a function called
has to be between 0
Problems dealing with numerical methods can be found in Miranda and Fackler, Ch. 2-4.
15