17

matlabNotes.pdf

Embed Size (px)

DESCRIPTION

matlabNotes.pdf

Citation preview

Page 1: matlabNotes.pdf

EPS4 Matlab 1

EPS4 Matlab

Contents

1 Introduction to Matlab 1

1.1 What is it? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 On-line help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.3 Using the Editor to create a new �le . . . . . . . . . . . . . . . . . . . . . . . . . 21.4 Laplace and Inverse Laplace transforms . . . . . . . . . . . . . . . . . . . . . . . 21.5 M-�les . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2 Problem sets 10

2.1 Problem set 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.2 Problem set 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.3 Problem set 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142.4 Problem set 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.5 Problem set 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

1 Introduction to Matlab

These notes mostly refer to Matlab under Windows on PC Caledonia. If you would like runMatlab at home you need to buy the program. There is a free alternative to Matlab calledOctave, which is very similar to Matlab. Most of the programs introduced in this document(apart from those requiring Symbolic Math Toolbox for Matlab) will run under Octave withat most minor modi�cations.The following notes provide a quick summary of Matlab to allow a quick start. The bookletAn Introduction to Matlab by David F. Gri�ths (downloadable through Vision) provides abroader introduction to Matlab.

1.1 What is it?

Matlab is essentially a programming language and is similar to C, Pascal, Fortran and otherwidely-used programming languages. (Technically it is a bit of a mixture between a compilerand an interpreter.) It also has many built-in functions for �nding approximate solutions ofmathematical problems, doing linear algebra etc. and producing good graphs of the results.Matlab runs on most standard computer systems (PCs, Macs, Unix workstations etc.) andlooks and behaves �almost� the same on each one.Matlab is widely used in higher education to teach numerical analysis and other topics becauseit is much easier to learn and to use than most other programming languages. However, onceyou have mastered Matlab, you will �nd it easy to learn any programming languages requiredfor work in the real world1 or further study. Matlab is increasingly being used in industry,both as a quick way to develop and test complex software, and for the facilities provided by themany add-on �toolboxes� tailored for di�erent applications. These toolboxes include �nancialmodelling, image enhancement, systems control, simulation and optimisation.

1real world = outside university

Page 2: matlabNotes.pdf

EPS4 Matlab 2

1.2 On-line help

• If you know the name of the command you want to �nd out about, type help *** in theMatlab command window to get information on the Matlab command *** or M-�le***.m (here *** stands for any command name e.g. mean, std, sum etc. listed in Section28 of the Introduction to Matlab). You may also type doc *** in order to get the sameinformation in a separate window.

• Other useful help facilities for Matlab can be found in the Mathematics folder on PC-Caldonia.

1.3 Using the Editor to create a new �le

• Make sure you are in your home directory.

• Click on File (at the top left of the Matlab command window) and select New and thenM-file.

• The Matlab Editor/Debugger window should open, and type the line below into it

avec = [1, 2, 3]

• Now save the �le by clicking on the File option at the top left of the editor window. SelectSave As and you should see a dialogue box opening. You need to specify a name for your�le and say what directory you want to put it in. You choose the directory in the Savein box: pull down the arrow at its right side until you come to something that starts withyour username (it is likely to be there already).

Type myprog.m in the File name box and then click on the Save button to save yourprogram. It is called myprog.m and it is stored in your home directory (corresponding toh: in Matlab).

• To test this out (and check whether you have saved the �le correctly), go back to theMatlab Command Window prompt � and type myprog to try to run the M-�le myprog.m.If the program has been saved correctly you should get the response

avec =

1 2 3

If it still doesn't work then go back and carefully follow the itemised steps above again. Itis very important that you learn how to save �les before you create anything complicated.

1.4 Laplace and Inverse Laplace transforms

To compute the Laplace and Inverse Laplace transforms we can use the functions laplace()

and ilaplace from the Matlab Symbolic Toolbox (not installed on PC Caledonia)To comute a Laplace transform of function f(t) = t we type at the Matlab prompt

>> syms t

>> f=t;

>> laplace(f)

ans = 1/s^2

Page 3: matlabNotes.pdf

EPS4 Matlab 3

To compute an inverse Laplace transform of function F (s) = 1/s2 we type

>> syms s;

>> F = 1/s^2;

>> ilaplace(F)

ans = t

The symbolic toolbox is not available in PC Caledonia labs, however, to perform the Laplacetransforms can use Maple instead. The syntax is quite similar to Matlab. To computeLaplace transform in Maple we can type

> with(inttrans):> f:=t:> laplace(f, t, s);

1

s2To compute an inverse Laplace transform we type

> with(inttrans):> f:=1/s^2:> invlaplace(f, s, t);

t

Matrices

Matlab only really deals with one type of object � rectangular matrices, whose entries caneither be numbers (real or complex), or text string characters. Matrices with only one row orcolumn can be treated as vectors, and 1× 1 matrices as scalars. (See Sections 5, 8 and 16 ofAn Introduction to Matlab.)Type the lines

x = [-2, 4, -8]

y = [3, 5, 7]

z = [1; 2; 3]

a = 5

A = [-1 0; 3 1]

to create two 1× 3 (row) vectors (x and y), a column vector (z), a scalar (a) and a 2× 2 matrix(A). Note that unlike some programming languages the case of variable names does matter inMatlab , so that a and A represent di�erent quantities. Matrices are usually entered in for

loops (An Introduction to Matlab Section 19) or using colon notation. Note that ending aline with a semicolon ; stops the answer being displayed. Try it out.Individual matrix entries can be referenced by indices in brackets: e.g. typing

x(2)

x(1,2)

A(2,2)

results in 4, 4 (the �rst two commands refer to the same element of x), and 1. Note that amatrix or vector will only accept positive integers as indices, so that B(12,197) is OK, whilstB(0,1), B(2,-3), or B(1.3,1) are not.

Page 4: matlabNotes.pdf

EPS4 Matlab 4

Matrix operations

Most of matrix operations are listed in Section 16 of An Introduction to Matlab. Note thatmany of these can be made to work entry-wise by typing a dot . before the operation � e.g.A*A is the matrix A2, whilst A.*A is the matrix with (i, j) entry equal to A(i, j)2. Con�rm thisin Matlab with the 2× 2 matrix A below:

>> A = [-1 0 ; 3 1]

A =

-1 0

3 1

>> A*A

ans =

1 0

0 1

>> A.*A

ans =

1 0

9 1

See Section 14 and 16.9 of An Introduction to Matlab.

Matrix eigenvalues and eigenvectors

To �nd eigenvalues of a matrix A we can use

>> A = [-1 0 ; 3 1]

A =

-1 0

3 1

>> d=eig(A)

d =

1

-1

Vector d will contain the eigenvalues of matrix A.To compute eigenevectors of the matrix A we type

>> A = [-1 0 ; 3 1]

A =

-1 0

3 1

Page 5: matlabNotes.pdf

EPS4 Matlab 5

>> [V,D]=eig(A)

V =

0 0.5547

1.0000 -0.8321

D =

1 0

0 -1

The columns of matrix V are eigenvectors of matrix A and the diagonal matrix D contains thecorresponding eigenvalues such that A*V = V*D.

Functions

These are introduced in Section 7 and listed in Section 28 of An Introduction to Matlab.Note that many scalar functions apply entry wise to matrices or vectors. Try out the followingexamples (remember that you can �nd out what the command *** does by typing help ***).

exp(x)

sy = sqrt(y)

abs(A)

floor(sy)

ceil(sy)

max(x)

For loops and colon notation

Type in the following lines

sum20 = 0

for i = 1:20

sum20 = sum20 + i

end

(the indentation isn't necessary but makes the code clearer). This code:

• initialises the variable sum20 to zero;

• for each integer i between 1 and 20 performs the command sum20 = sum20 + i.

The command i = 1:20 is an example of colon notation. It means �all the integers between1 and 20, starting with 1 and ending with 20�. If a, b and c are numbers, then a:b:c means �allthe numbers a, a+b, a+2b, . . . ending at or just before c�. The syntax is first:increment:last.If you don't include an increment (e.g. i=1:20 above), then it is assumed to equal 1.Type in the following lines to get a better idea of what is going on.

Page 6: matlabNotes.pdf

EPS4 Matlab 6

1:2:10

5:-7:-30

14.32:-0.2:8.5

1:20

1.24:9.1

Why does the last example give a vector whose last element is 8.24 and not 9.1?An Introduction to Matlab Sections 19 and 20 deal with for loops and related things in detail.

Plotting graphs

The simplest plot command has the form plot(x,y), where x and y are vectors of the samelength, n say. It plots a graph of the points (x1, y1), (x2, y2), . . . , (xn, yn). For example, typein the following lines to get a plot of sin t against t.

t = [0:0.01:2*pi];

v = sin(t);

plot(t,v)

Section 10 of An Introduction to Matlab describes how to make multi-plots, 3D plots and howto change the axes scaling and line styles. Axis labels and a title can be added using the xlabel,ylabel and title commands; e.g. try out the command ylabel('sin t')

Text strings

The argument of the above ylabel command is an example of a text string � i.e. a collectionof characters surrounded by single quotes. Another example isst = 'my name is Frankenstein'

Note that both quotes are the same. Commands like disp, input and error use text strings.Another useful command is num2str, which converts a number into a string. As an example ofhow to use it and a slightly more complicated string expression, typetitle(['plot of sin t up to ', num2str(2*pi)])

to label your graph.Note that in the above example using title, the string has more than one element. If more thanone string element is used (typical when mixing words and numbers), then the string elementsto be joined together must be enclosed in square brackets and separated by commas.

1.5 M-�les

Matlab can be used in two main ways. You can either type instructions directly at the promptor make up a �le or �les containing the instructions you want Matlab to execute and feed this�le (called an M-�le) to Matlab. An M-�le is a computer program written in Matlab's ownlanguage. Typing commands at the prompt is �ne if you want to execute single commands, buterrors usually creep into the typing of longer expressions and sequences of operations and it is apain having to retype things used over and over again. In general, you should use M-�les, andthe mechanism for creating them is described in Section 1.3 above.There are two di�erent kinds of M-�les, script �les and function �les, which act in slightlydi�erent ways. Script M-�les act as a shorthand for a sequence of Matlab commands and area bit easier to use than function M-�les. We discuss both types of M-�les below, and Sections13 and 21 of An Introduction to Matlab also describe them in detail.

Page 7: matlabNotes.pdf

EPS4 Matlab 7

A sample script M-�le

Suppose we want to write an M-�le to �nd the sum of the �rst 20 integers, instead of typing thecommands at the Matlab prompt. The following �le which we shall call S20.m (note that allM-�les end in .m) does what is required. Follow the instructions in Section 1.3 and create thisexample �le.

% S20 Find the sum of the first 20 integers

%

% Computes and outputs the sum 1 + 2 + ... + 20

% in the variable sum20.

% Note that this line is ignored.

sum20 = 0; %initialise sum20 to zero

for i = 1:20

sum20 = sum20 + i;

end

disp(['The value of sum20 is ',num2str(sum20)])

Typing the name S20 at the Matlab prompt will execute the M-�le and should result in theline

The value of sum20 is 210

Note that if you miss the semicolon from the line sum20 = sum20 + i then you will get a wholelot of unwanted output. The semicolon suppresses the output.Create the �le and try it out (make sure that you have learnt how to Save �les �rst). Typinghelp S20 will print out the lines at the top of the �le that start with a % (the comment lines),up to the �rst line that doesn't start with a %. This is a very useful way of letting yourself (andanyone else who uses your Matlab programs) know what a particular �le does. It is good styleto always start an M-�le with a comment line. Matlab ignores any commands that follow a %,and so comments can be inserted in the body of the program after a %.

Sample function M-�les

The following �le (called mkvec.m) is a simple function M-�le.

function v = mkvec(x)

%MKVEC Construct the vector [1, x, x^2, x^3] from x

% mkvec(x) returns the vector [1, x, x^2, x^3]

v = [1, x, x^2, x^3];

It contains an input argument (x), the 4�component vector output argument v and a functionstatement (the �rst line). Write and save the �le and then type mkvec(2) at the command line.You should get the result

ans =

1 2 4 8

Page 8: matlabNotes.pdf

EPS4 Matlab 8

You can use the M-�le to create named vectors � for example if you type w = mkvec(6) thenyou obtain

w =

1 6 36 216

instead.Function M-�les can have more than one input argument � e.g. the �le mkvec2.m below:

function v = mkvec2(x,n)

%MKVEC2 Construct the vector [1, x, x^2, ..., x^n] from x and n

% mkvec2(x,n) returns the vector [1, x, x^2, ..., x^n]

for k = 0:n

v(k+1) = x^k;

end

and more than one output argument � e.g. the �le mkvec3.m below:

function [v, len] = mkvec3(x,n)

%MKVEC3 Construct the vector [1, x, x^2, ..., x^n] from x and n

% [v, len] = mkvec3(x,n) returns the vector

% v = [1, x, x^2, ..., x^n] and its length len.

for k = 0:n

v(k+1) = x^k;

end

len = length(v);

You can also use dot operations to avoid loops in the previous example, e.g. as in the �lemkvec3a.m below:

function [v, len] = mkvec3a(x,n)

%MKVEC3A Construct the vector [1, x, x^2, ..., x^n] from x and n

% [v, len] = mkvec3(x,n) returns the vector

% v = [1, x, x^2, ..., x^n] and its length len.

% Does not use loops

k = 0:n;

v = x.^k;

len = length(v);

See Section 21 of An Introduction to Matlab for more details.

Page 9: matlabNotes.pdf

EPS4 Matlab 9

The Matlab ODE solvers

The Matlab ODE solvers are written to solve systems of DE's of the form

dx1dt

= f1(t, x1, x2, x3, . . . )

dx2dt

= f2(t, x1, x2, x3, . . . )

dx3dt

= f3(t, x1, x2, x3, . . . )

. . .

i.e.dx

dt= F (t, x).

There are several built-in ODE solvers from which we can chose, e.g., ode45, ode23, ode113,ode15s, ode23s, ode23tb (each solver has its advantages and disadvantages).Below is a sample code for the solution of the system of DEs

d

dt

[x1x2

]=

[−1 −11 −2

] [x1x2

]using the ode45 solver.

function main

% Use ODE45 to solve

% dx_dt(1) = -1*x(1)-1*x(2)

% dx_dt(2) = 1*x(1) -2*x(2)

options=odeset('RelTol',1e-6); %set error tolerance for the ODE solver

xinit = [1;1]; %initial condition

tspan = [0,5]; %time interval

[t,X] = ode45(@F,tspan,xinit,options); %call the solver

%plot the results

figure

hold on

plot(t,X(:,1));plot(t,X(:,2),':')

legend('x1','x2');ylabel('x');xlabel('t')

return

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% rhs function x'=F(t,x)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [dx_dt]= F(t,x)

M = [-1,-1; 1,-2];

dx_dt = M*x;

return

Page 10: matlabNotes.pdf

EPS4 Matlab 10

2 Problem sets

2.1 Problem set 1

1. (a) What is the semi-colon for?

(b) Generate the row vector x = (0.6, 0.7, . . . , 1.4, 1.5) using 2 colons and three numbers.

(c) Find the transpose of the vector x in (b).

(d) If A and B are n×n matrices, what is the di�erence between A ∗B and A. ∗B? Tryit out for some 2× 2 matrices that you choose yourself.

2. Use the colon notation to generate the vector x = (0.6, 0.7, . . . , 4.4, 4.5).

(a) Find the sum of all its elements.

(b) Find its length.

(c) Find the sum of the squares of all its elements.

Use length and sum and see Section 14.4 of An Introduction to Matlab.

3. Generate the vector x = (0, 0.1, 0.2 . . . , 10).

(a) Find the vector s whose jth element is the sine of the jth element of x.

(b) Plot vector s against x using the line style �stars� and put appropriate labels on thegraph.

See Section 10 of An Introduction to Matlab.

4. (a) Enter the matrix

A =

1 1/2 1/31/2 1/3 1/41/3 1/4 1/5

.

(b) Enter a vector b = (3, 1.9167, 1.4333)T (i.e. b is a column vector).

(c) Find the solution x to the linear system Ax = b (hint: use \).Note that the matrix A is the 3 × 3 Hilbert matrix, and can be de�ned in Matlab moresimply by using the command A = hilb(3).

5. What e�ect do the commands format short e, format long e and format compact haveon Matlab output ? Try it out by typing pi after the various format commands. (Seehelp format).

6. Create

(a) a 9× 9 identity matrix,

(b) a 7× 9 zero matrix,

(c) a 4× 6 matrix of ones.

Use (eye, zeros, ones).

Page 11: matlabNotes.pdf

EPS4 Matlab 11

7. (a) Use the editor to create a function M-�le called anysump.m which takes as input thepositive integer N , and as output the result p of the summation

p =

N∑j=1

j−2.

(b) Compute from the Matlab command window, the value of the sum forN = 5, 10, 15, 20.

8. (a) Follow the examples in Section 10 of An Introduction to Matlab to plot f(x) =x2 + x− 1 with a �dashed� line style. Use x = −5 : 0.05 : 5 for the x coordinates.

(b) Add labels to the x and y axes and add your name as the title of the graph.

(c) Annotate the graph to show which curve is being depicted. (legend, see the Lecturenotes)

9. (a) Follow the examples in Section 10 of An Introduction to Matlab to plot f(x) =x+ x2 − x3/10− 10 with a �dashed� line style and g(x) = cos(x) with a solid line inthe same graph. Use x = 0 : 0.05 : 10 for the x coordinates.

(b) Add labels to the x and y axes and add your name as the title of the graph.

(c) Annotate the graph to show which curve is which and place the text �f=g here� nearwhere the curves cross. (legend, text, see the Lecture notes)

10. Write a function M-�le that takes as input the positive integer n and number r, andoutputs the sum

n∑k=1

kr.

Use it to check the identity

n∑k=1

k2 =n (n+ 1) (2n+ 1)

6

for various values of n.

11. Plot an (x, y) graph for x ∈ [−5, 5] when y = sin(x)+ 1−x. Use the information from thegraph to help the built-in function fzero �nd the root of the equation sin(x) + 1− x = 0.

Page 12: matlabNotes.pdf

EPS4 Matlab 12

2.2 Problem set 2

1. Produce 4 separate graphs against x for x ∈ [−π, π] (labelled appropriately), of the func-tions (a)-(d) below all in the same Figure window (subplot).

(a) x3/20 + x2/10,

(b) cosx,

(c) sin2 x,

(d) e−x2.

2. (a) Write a function M-�le using for loops to de�ne the N ×N tridiagonal matrix A andvector b given by

A =

β γ 0 . . . 0

α β γ...

0. . .

. . .. . . 0

... α β γ0 · · · 0 α β

, b =

sin(1)sin(2)· · ·

sin(N−1)sin(N)

,

which will work for any integer N ≥ 3. Make sure that b is a column vector. Thematrix A is called tridiagonal because all its entries are zero apart from those on orimmediately next to the diagonal.

(b) For α = 1, β = 4, γ = −1, �nd the solution x of Ax = b in the case N = 4, and�nd the 42nd element of the solution x in the case N = 199. (Use the backslash \command.)

(c) Use the command eig to �nd the eigenvalues and eigenvectors of the matrix A withN = 5, α = γ = 1, β = 2.

3. So far we have seen two ways of solving Ax = b for x where A is an N ×N matrix and ban N vector:

Method Matlab commands

Gaussian elimination x = A\b;

Full inversion Ai = inv(A); x = Ai*b;

We would like to test which method takes the least cpu time.

(a) Write an function M-�le where the input is the size N and the output is the time(cputime) in seconds it takes by each of the two methods to compute the solution ofAx = b for randomly chosen A and b (rand).

(b) Then write a second M-�le for depicting the two resulting times forN = 100, 150, 200, . . . , 800.Label the graph appropriately.

4. Newton's method for �nding a solution of the equation f(x) = 0 is the following iteration.Step 1 Make a guess at the solution (call it x1),Step 2 calculate the sequence of values x2, x3, . . . from

xk+1 = xk −f(xk)

f ′(xk)for k = 1, 2, 3 . . . ,

Page 13: matlabNotes.pdf

EPS4 Matlab 13

Step 3 stop when |xk+1 − xk| < TOL, where TOL is a small number supplied by the useror if we reach k = 100 without �nding a solution.

(a) Write a function M-�le with input: TOL, initial guess x1 and output: the Newtonmethod approximation of the solution of cos(x) = x, and the number of steps takento get there. It will make life easier for you if you write the M-�le in such a way thatthe equation to be solved can be changed easily.

(b) Type format long e to show numbers to full precision before the next part.

(c) Find the root of cos(x) = x using the built-in function fzero �rst of all, then applyyour Newton function to the equation cos(x) = x with TOL= 10−6 and try twodi�erent starting guesses x1 = 1.4 (which works) and x1 = −1.4 (which doesn't).Does you solution agree with that from fzero? Now try a wider range of startingguesses −2 ≤ x1 ≤ 2. Is there a pattern in which starting guesses work and which donot? (for, if, break).

Page 14: matlabNotes.pdf

EPS4 Matlab 14

2.3 Problem set 3

1. (a) Follow the example in Section 23 of An Introduction to Matlab to produce a meshplot of z = x sech(x2 + 2y2) over the square [−2, 2]× [−2, 2] in the subplot(2,2,1).

(b) Now produce a contour plot of the function (contour) in subplot(2,2,2) and markit with a star at its maximum.

2. The derivative of a well-behaved function f(x) with respect to x can approximated byvarious �nite di�erence approximations:

(F) : f ′(x) ≈ f(x+ h)− f(x)h

, (C) : f ′(x) ≈ f(x+ h)− f(x− h)2h

.

The labels F and C stand for �forward� and �central� respectively. The number h is usuallyrelatively small, and the approximations should, in theory, get better as h decreases.

(a) Write a function M-�le that takes as input x and h, and outputs the forward andcentral approximate derivatives of f(x) = sin−1(x).

(b) Set x = 1/2 and plot the modulus of the error in the results against h for h =10−10, 10−9, . . . , 10−2. Which gives better results and why do they stop getting betteras h decreases? Use the loglog function to plot, and label the graph appropriately.

Page 15: matlabNotes.pdf

EPS4 Matlab 15

2.4 Problem set 4

1. The Midpoint rule gives a relatively reliable way to approximate integrals which cannoteasily be worked out exactly. To �nd

∫ ba f(x) dx, the interval a ≤ x ≤ b is split into N

strips of equal width, and the function is assumed to be constant over the strip makingit easy to integrate. The contributions from all the strips are added up to give the �nalapproximation. The approximation formula that results is

I ≡b∫

a

f(x) dx ≈ hN∑j=1

f(xj) ≡ IN

where the width of the strips is h = (b − a)/N and the mid points of the strips arexj = a+h(j− 1

2). The error in the approximation IN is roughly one third of the di�erencebetween IN/2 and IN .

(a) Write an M-�le to approximate the integral∫ 21 sin(x3) dx with N = 8, 16, 32, . . . , 1024

strips.

(b) Tabulate the result to full precision and make an estimate of the error in the results.

2. One of the best known examples in dynamical systems and chaos theory is the LogisticMap. It is de�ned by xk+1 = λxk(1− xk) for k = 1, 2, . . . with starting value x1 ∈ (0, 1).The constant 0 < λ ≤ 4 controls the type of behaviour observed.

(a) Write a function M-�le with inputs λ (controlling parameter), N (number of steps)and x1 (starting value), and output the vector (x1, x2, . . . , xN ).

(b) Use this to plot xk vs k for various values of λ and x1 in four horizontal strips on thesame �gure. (subplot).

(c) Try the case λ = 3.7, N = 100 with x1 = 0.7, 0.7 + 10−9, 0.7 + 10−6, 0.7 + 10−3 andcomment on how many steps it takes the results to deviate from the x1 = 0.7 case.

(d) Try the case x1 = 0.7, N = 500 with λ = 3.3, 3.5, 3.739, 3.835 and comment on thepattern the solution settles into. (It might help to list the last 10 numbers in thesequence in each case.)

3. Euler's method for solving the �rst order di�erential equation

dy

dt= f(y, t)

for 0 ≤ t ≤ l subject to the initial condition y(0) = a.Step 1 Fix a small value h > 0.Step 2 Set t0 = 0 and tn = tn−1 + h.Step 3 Find an approximation of y step-by-step from the recursion

yn+1 = yn + hf(yn, tn)

with initial value y0 = a.

If h is su�ciently small, this often produces a good approximation of the solution to theabove �rst order initial value problem.

Page 16: matlabNotes.pdf

EPS4 Matlab 16

(a) Write an M-function with inputs the parameter h and length of the interval l, andoutput the two vectors t and y obtained by applying Euler's method to the initialvalue problem

dy

dt= (1− t)y, y(0) = 1.

(for end).

(b) The exact solution of this ODE can actually be found analytically, y(t) = et−t2/2.

Plot a graph comparing the exact and the approximate solutions for 0 ≤ t ≤ 5. Usea blue �lled line for the exact solution and a green dashed line for the approximatedone. Label the graph appropriately. (plot).

(c) Use one of the built-in Matlab ODE solvers (e.g., ode15s) to solve the above ODEand compare the resulting solution to the one obtained by the Euler's method andto the exact solution.

Page 17: matlabNotes.pdf

EPS4 Matlab 17

2.5 Problem set 5

1. UseMatlab (orMaple) to compute Laplace transforms from the Table of Laplace trans-forms from the lecture notes and from the Tutorial exercises.

2. Use Matlab (or Maple) to �nd inverse Laplace transforms of the functions from theTutorial exercises.

3. Solve the LCR circuit example problem from the Lecture notes using theMatlab built-inODE solvers and compare the computed solution to the exact solution from the lecturenotes.

4. Use the Matlab build-in ODE solver to solve the following system of ODEs for t ∈ (0, 5)

dx1dt

= x1 + 2x2 ,

dx2dt

= 2x1 − 2x2 ,

x1(0) = 2 x2(0) = 1, ,

Compare the computed solution with the exact solution from Section 3.5 of the Lecturenotes.

5. Use the Matlab build-in ODE solver to solve the following system of ODEs for t ∈ (0, 5)

dx1dt

= −4x2 + δ(t− 3) ,

dx2dt

= x1 ,

x1(0) = 0 x2(0) = 1, ,

where δ(t) is the Delta function (Hint: replace the delta function by an approximationδ̃(t) = 1/ε for t ∈ (0, ε) for a su�ciently small ε, e.g. ε = 0.01). Compute for di�erentvalues of ε and compare the computed solution with the exact solution (cf., Lecture notesFigure 3.2)

x2(t) =

{cos (2t) t < 3 ,cos (2t) + 0.5 sin (2t− 6) t ≥ 3 .

[�ubomír Ba¬as (based on the notes by Lyonell Boulton)]