Sunteți pe pagina 1din 15

SDPE

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.

To get information about a specic command, type

 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:

Applied Computational Economics and Finance


CompEcon toolbox

Homepage, you can also download the so-called

by Mario J. Miranda and Paul L. Fackler.

On Fackler's

, which contains a lot of useful functions.

Basics

2.1 Entering and displaying data

Data is entered in Matlab in matrix form. For example, the

16
5
A=
9
4

44

matrix

3
10
6
15

2 13
11 8

7 12
14 1

is generated by typing:

 A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1];


To create a

row vector type:

 B = [1 2 3 4]
For a

column vector type:

 C = [1; 2; 3; 4]
A scalar is a

11

matrix:

 D = 5

Note the following:

The '=' assigns a value to (the variable)


under the name




A;

To enter a matrix, use

or, in other words, it stores the matrix in the workspace

[ ];

';' ends a row; within a row, ' ' indicates a new column.

To change a variable, just assign a new value to it:

 C = [2; 3; 4; 5];
You can also assign a new value by using the old:

1 alex.schmitt@iies.su.se.

Current version: January 26, 2011

 C = C - 1;

To delete a variable from the workspace, type

 clear name
To empty your workspace, type

clear all.

can be displayed by either typing just

 A
Or, more complicated but nicer, with the

disp

command:

 disp('Our matrix A is a Durer matrix'); disp(A);


Aij

is the element in the ith row and

To display one element of

j th column of A.

In Matlab, the corresponding command is

A(i,j).

type, for example, type

 A(3,2)
For a vector it is enough to type

 B(3)

It is also possible to choose and display parts of a matrix. For example,






A(:,1)

displays the rst column of

A(1:3,1)

A.

':' stands for all elements in this column.

displays only the rst three elements of the rst column of

A.

A(1:3,1:3)

displays the matrix without the last row and the last column.

A([1 3],2)

displays the second column of the rst and third row.

To suppress output in your command window, end your command with a semicolon ';'.

2.2 Basic operations

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

only works if the number of columns in

is equal to the number of

 A * B
Piece-wise multiplication:

 A .* C
This multiplies each element in

with the corresponding element in

the same dimension.

Piece-wise

operators:

 A.2 squares each element in A.


 sqrt(A) takes the square root of each element in A.
 log(A) takes the natural logarithm of each element in A.

Other useful commands:

 diag(A) gives the diagonal of A (a vector).


 sum(A) sums the columns, sum(A,2) sums the rows of A.
2

C.

Again, the matrices need to have








sum(diag(A))

sums the diagonal of

max(A) (min(A))
max(A,[],2)
A'

gives the maxima (minima) for each column.

gives the maxima for each row.

gives the transpose of

inv(A)
A(:)

A.

A.

gives the inverse of

A.

vectorizes a matrix.

Basic statistics commands:

 mean(N): mean (for each column of N)


 median(N), var(N), std(N)
 cov(N):variance-covariance matrix (if N is a matrix)

2.3 Generating vectors and matrices

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

... of random numbers uniformly distributed over (0,1):

R = rand(3,3);

... of standard-normally distributed random numbers :

N = randn(3,3);

... the identity matrix:

I = eye(3,3);

We can also create matrices by

concatenating

other matrices.

For example, using the four 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

dimension of a matrix, use the size command.

 [m,n] = size(ZORN) gives the dimension of ZORN (as a 1 2 vector).


 m = size(ZORN,1) gives the number of rows in ZORN.
 n = size(ZORN,2) gives the number of columns in ZORN.
Sequences






are created in the following way:

E = 1:10

constructs a row vector of all natural numbers between 1 and 10.

F = 1:2:10

constructs a row vector with an increment of 2 from 1 up to 10.

G = 100:-20:10

constructs a row vector with an increment of -20 from 100 down to 10.

H = linspace(1,5,10)

constructs a row vector with 10 elements, starting at 1 and ending at 5.

Writing programs in Matlab

Instead of using the command window, it is much more convenient to write a program (

M-le)

that

includes all your commands and operations.

Useful features of M-Files include the

diary

command (that creates a text le that creates your results)

and comments.

Comments

can be added by starting a line with the percentage sign '%'. Use comments frequently in

order to explain what you do in each step of the code.

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 look at some output (e.g. graphs) before continuing the program.

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.

Conveniently, Matlab informs you if the le

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.

Loops and conditional statements

4.1

for-Loops
for-loop

For example, use a loop to write a

repeats a group of statements a xed, predetermined number of times.

following property:

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 have the

 Z = zeros(20,1);
 for i = 1:19
 Z(i+1) = Z(i) + 0.25;
 end

4.2 Relational operators

Relational operators perform element-by-element comparisons between two matrices:

==, =, >, <, >=

, <=.

logical

They return a

matrix of the same size, with elements set to 1 where the relation is true and

elements set to 0 where it is false. Examples:

- 1 > 2;
- eye(2) > zeros(2);

You can combine such logical expression with the operators

- 1 < 2 && 2 > 3;

|| (or )

and && (and) :

4.3 Logical operators


all(A):

returns a logical 1 for each column of

for all rows of

any(A):

A.

Note:

that does not contain a zero.

that contains at least one nonzero element.

returns a logical 1 for each column of

does the same for all rows of

all(all(A))

logical 1 if

returns a logical 1 if

some elements in

isinteger(A):
isreal(A):

A.

all elements in

are nonzero. Similarly,

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.

are real numbers.

does the same

any(any(A))

all(A,2)
returns a

4.4

while-Loops
A

while-loop

repeats a group of statements an indenite number of times under control of a logical

condition, i.e. as long as a logical expression is true.

For example, write the loop above as a








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,

 if x > 0; disp('x is positive'); end











elseif

By using

if x > 0

and

&&

else,

you can specify commands in case the expression is not true:

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

More useful commands

Here is a somewhat arbitrary list of other useful commands in Matlab:

round(x)
ceil(x)

returns the integer that is closest to

x.

returns the closest integer greater than

floor(x)

returns the closest integer lower than

x.
x.

find(A) locates all nonzero elements of matrix A and returns a


find(A > 10) locates all elements in A that are greater than 10.
error('message ')

vector with their positions.

Similarly,

in combination with an if-expression stops an operation, for example a loop, in case

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,

and stop it with

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,

separate from the workspace you working in.

All commands you have seen so far are functions, e.g.

Data

und

size(Data,1)

is a function with input arguments

and the number of rows as output argument. In addition to the already available functions,

you can write your own functions.

A function has always the same structure. You must declare it to be a function and dene output, name
and input.

Suppose you want to write

rows(A)

instead of

size(A,1) in order
rows(A):

to get the number of rows. You can

write a function that produces this every time you type

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

Matlab, write the following function:

function y = fun1(x)
y = min(exp(2*x+2),20);

under the name of the function (here:

rows.m)

Save the M-le

Some advice: store all your functions in one directory (e.g. 'Myfunctions') and add this directory to the

- do that with every function you create!

search path (FileSet Path) such that Matlab nds it!

6.1 Global vs. local variables

global variable can be retrieved from anywhere, in any program (script or function) in Matlab.

local variable is specic to the program youare running.

For example,

in the function

rows

is a local variable. You may have

in the main program; they will

be dierent variables.

If you want to dene a global variable, write

For example, the function

mult.m

global x

in

uses the global variable

both the function and main le.

x:

PROGRAM
...
global x;
x=1:10;
y=2;
z=mult(y);
...

FUNCTION
function a=mult(b);
global x;
a=x*b;

6.2 Inputs and Outputs

A function can have many inputs and many outputs. For example, consider
two inputs:

function [a,b,c] = fun3(x,y)


a = x + y;
b = x - y;
c = x * y;

fun3

with three outputs and

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

command that returns the

number of inputs, together with some if-expression. For example,

function [a,b,c] = fun4(x,y)


if nargin == 1
a = x + 5; b = x - 5; c = x * 5;
else
[a,b,c] = fun3(x,y)
end

The last example also shows that functions can call

other functions.

Plots

7.1 Line plots


plot(x,y)

produces a graph of a vector

versus a vector

x.

For example,

 x = 0:100;
 y = 2 * x;
 plot(x,y)

To make it more fancy:






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

If you want to produce several plots in one window, use

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

The rst two arguments in


as an it as an array with
(and must therefore be a

Start every graph with

figure.

In that way, you get output for all graphs in your program. Moreover, it

allows you to save graphs, either as a jpeg- or a pdf-le:

 print djpeg 'Figures/graph1';


 print dpdf 'Figures/graph1';

7.2 Bar Plots

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

is a vector whose elements specify the midpoint

among. For example,

plots the frequency distribution of

hist(x,y),

among 25 equally sized intervals.

If you prefer the relative frequency distribution instead, type:

- [N M] = hist(x,-20:2.5:40);
- N = N/size(EP,1);
- bar(M,N)

The rst command gives the absolute frequencies in

N,

the second normalizes and the third plots using

the normalized frequencies.


Frequency distribution of monthly excess returns, 1932-2005
0.35

0.3

Frequency, fraction

0.25

0.2

0.15

0.1

0.05

0
-30

-20

-10

10
Return

20

30

40

50

7.3 More Plots

Suppose you want to plot a function with more than one argument. For example, let's plot the well-known

Y = K L1 over ranges for


using the meshgrid command:

Cobb-Douglas production function


function, we have to dene a grid,

K = 1:10;
L = 0:0.1:1;
[x,y] = meshgrid(K,L);
z = x.alpha .* y.(1 - alpha);

meshgrid

allows us to get function values for each possible K-L-combination.

One way to plot the Cobb-Douglas function is as a

capital and labor. Before plotting the

figure
contour(x,y,z,n)
title('Cobb-Douglas production function')
xlabel('K')
ylabel('L')
zlabel('Y')

contour plot:

n isoquants, for n dierent levels of output


contour(x,y,z,v), where v is an increasing vector

This graph should look familiar from Microeconomics: it shows


Y. If you want to specify these levels of output, use
containing those levels.

Another possibility to illustrate the function is as a three-dimensional

- figure
- mesh(x,y,z)

mesh plot:

title('Cobb-Douglas production function')


xlabel('K')
ylabel('L')
zlabel('Y')

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!';

S as a vector, namely a 1-by-14 row vector,


S(2) returns a, S(14) returns !.

Note that Matlab treats


element. For example,

You can display your string with the

disp

command:

disp(S).

fprintf allows you to embed numerical data within a


- x = rand(10,1);
- fprintf('The mean of x is %.4f.\n',mean(x))

where each character constitutes one

string. For example:

You can also embed more than piece of data:

- fprintf('The mean of x is %.4f and its ...


variance is %.4f.\n',mean(x),var(x))

Matlab inserts data whereever you put an


displayed, here with four decimals.

\n

%. .4f

gives the format in which you want to have the data

indicates a new line.

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.

You can generate an empty cell array with


accessed by indices with

{}.

- 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

fprintf in a loop, you can report multiple results more


- mx = [mean(x); var(x); std(x)];
- for i = 1:3
fprintf(['The ',S{i},' of x is %.4f.\n'],mx(i))
- end
Using

quickly:

Basic Numerical Methods

Numerical methods are a very important application in Matlab (and when using software in general). Examples
for basic methods are:

Numerical optimization

Solving systems of linear and non-linear equations

Numerical dierentiation and integration

Function approximation

10.1 Numerical dierentiation

f (x).
f (x) is

The goal of numerical dierentiation is approximating the derivatives of a function

Of course, we

could always try to nd the derivative analytically, and then use these. However, if

a complicated

function, this might be hard.

Moreover, using numerical approximations has the advantage that you

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

for the rst derivative, where

is a small number.

That is, we approximate the

f 0 (x)

with a nite

dierence.

Similarly, we can approximate the second derivative in the following way:

f 00 (x)

f (x + ) 2f (x) + f (x )
.
2

These values are straightforward to compute in Matlab:

- eps = 1e-06; x = 10;


- fd = (fun5(x + eps) - fun5(x-eps))/(2*eps);

Even faster is using the CompEcon toolbox functions


second):

- fd = fdjac('fun5',10);
- fdd = fdhess('fun5',10);

10

fdjac

(for the rst derivative) and

fdhess

(for the

10.2 Optimization

There are numerous methods to do numerical optimization, i.e.

to nd the numerical optimum of a

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

attains its maximum

x)

and use the

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

approximately; a valuable information for the more advanced methods.

10.2.1 The Gradient Method

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 (x) f (x0 ) + f 0 (x0 )(x x0 ).

We can also take a Taylor approximation for the rst derivative of

f:

f 0 (x) f 0 (x0 ) + f 00 (x0 )(x x0 )

We want to nd

x .

We know that at

x , f 0 (x ) = 0.

Hence,

f 0 (x0 ) + f 00 (x0 )(x x0 ) 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

and use this to compute:

f 0 (x0 )
.
f 00 (x0 )

(1)

Most likely, unless your initial guess was very good,

x1 6= x .

However,

hence should be a better guess. Thus, just repeat the step in (1) with

x1 should be closer to x than x0 ,


x1 as the guess to nd x2 - and so

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 )

In other words, you

iterate

on (1), i.e. repeat the step several times, until you are close enough to

stopping rule) is fullled, e.g.

That is, you stop this algorithm if some criterion (

you stop if your updated guess is approximately the same as the previous one.

One way to implement this stopping rule is to stop if

|xn+1 xn | < 
where

is a very samll number, e.g.

 = 1012 .
11

if

xn+1 xn .

x .

That is,

To implement this algorithm in Matlab, we will use a

- while dist > 10(-12)


fd = fdjac('fun5',x0);
fdd = fdhess('fun5',x0);
x = x0 - fd/fdd;
dist = abs(x - x0);
x0 = x;
- end

while-loop:

The rst line gives the stopping rule: the loop goes on as long as the variable

x0and
x x0.

further below, is dened as the dierence between the old guess


In other words, this line tells Matlab to execute the loop until

For the derivates

fd

and

dist (which, as you can


x) is greater than .

the new

fdd, our knowledge about numerical dierentiation comes in handy.


fdjac and fdhess from the CompEcon toolbox. Equivalently, I

most easy way and use the

I do it the
could also

compute the nite dierences seen above.

The fourth line is the iteration rule found above, so


last line, we have to update

x0

f 0 (x) = 0.

points close to

But note that such an

In other words, once you've found

is the old value and

is the updated one. In the

Note that there are a couple of potential problems with the Gradient method. First, we look for an
that

x0

before the next iteration of the loop starts.

x,

x such

is not necessarily a maximum, but could as well be a minimum.

check if it's really a maximum (e.g. by evaluating the function at

x).

A function might have more than one

global maximum.

local

maximum, so you don't know for sure if you've found the

Try dierent initial guesses to see if there are several optima.

Finally, there is no guarantee that the algorithm converges to

x .

In that case

changing your initial guess

might help.

10.2.2 In-built optimization functions

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

nds the minimum of a function of one variable within a xed interval.

fminsearch is used in the following way:


x = fminsearch('f',x0); or
x = fminsearch(@(x) f(x),x0);
where f is a function name and x0 denotes an initial
In general,

Note that fminsearch nds a function's


x = fminsearch('fun5',1);

guess.

minimum rather than the maximum. So typing

gives you the minimum of the function - which (obviously) is not well-dened.

To nd the maximum, just minimize over the

negative function values. That is, typing

[x,opt] = fminsearch(@(x) -fun5(x),1);


will do the trick. opt stores the function value

at the optimum.

10.3 Solving systems of equations

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

The root is the

value(s) that solves this

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.

10.3.1 Linear systems of equations

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

In order to solve for the vector

1
3
2

1
0
1

rewrite the system using matrix notation:


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

Hence, (2) can be written as

(x1 , x2 , x3 ),

Ax = b.

x, note that x = A1 b, A1
x in the following way:
- x = inv(A) * b;
To solve for

denotes the inverse of

A.

In Matlab, after dening

and

b,

we

can solve for

Alternatively - and recommended for more complicated problems - use the

- x = A\b;

backslash operator:

10.3.2 Nonlinear equations

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,

we get the following

optimality condition:

(y s) R(y + Rs) = 0.
This is an example of the so-called

Euler equation (an intertemporal optimality condition).

We want to nd optimal saving, i.e. solve the Euler equation for

s.

The special form of the utility function

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

a, b such that the root x lies in between those: x [a, b]. As x is


= 0), f (a) and f (b) should have dierent signs. You then guess that x0 = 0.5(a+b) and check
the sign of f (x0 ). If it has the same sign as f (a), the root must be somewhere between x0 and b. Hence,
update your guess by x1 = 0.5(x0 + b). If it has the same sign as f (b), update it by x1 = 0.5(x0 + a).

The idea is that you start with two values


a root (f (x)

Iterate on this algorithm until

f (xn ) 0

Here's the algorithm. Again, I use a


satised. Start by Also, choosing

(i.e. use a stopping rule).

while loop which stops as


b that bracket the root:

soon as the stopping rule (f (x)

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

A useful command here is

Note that if the root is not bracketed, there is no convergence and the algorithm will run forever. In that
case stop (Crtl

which gives you the sign of a variable.

+ C ), and use dierent values for

If you solve a function with just one variable, one

b.

in-built Matlab function you can use it fzero,

uses the Bisection method. Its syntax is similar to

- s = fzero('euler',s0);
Note that s0 species an initial

and

fminsearch:

which

guess.

10.3.3 Systems of non-linear equations

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

deal with this type of problem.

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

we then have two equations - the Euler equation and

c
0 (1 + r)c1 = 0
y
c1
y
=0
c0 +
1+r
1+r

To solve this system in Matlab, dene a function le called

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

Note that this function has a vector

euler,

containing these equations:

as input, which contains two elements,

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.

To solve the system, guess an initial value for

- c0 = ones(2,1);
- c = fsolve('euler2',c0);

and use

14

fsolve:

11

Advanced Numerical Methods

11.1 Value Function Iteration


(to be completed)

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.

2. Write a program that uses a loop to write a


have the following property:

whose elements

A. Now perform the following operations: 1) store


B; 2) get the inverse of A; 3) replace this matrix with one containing its squared elements; 4)

3. Write a program that generates a random 4-by-4 matrix


the matrix as

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 =

5. Write a function called

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

cobbdouglas that has one mandatory input alpha (which


K and L - all scalars! - and does the following:

has to be between 0

and 1), and two optional inputs

cobbdouglas(alpha) returns a mesh plot of the Cobb-Douglas production


, over a xed range for capital and labor, e.g. 0 < k < 10 and 0 < l < 1;
cobbdouglas(alpha,K,L)
(K, L) (but no plot!).

function with parameter

returns the function value of the Cobb-Douglas production function at

Problems dealing with numerical methods can be found in Miranda and Fackler, Ch. 2-4.

15

S-ar putea să vă placă și