Professional Documents
Culture Documents
Contents
1 Introduction to Matlab 1
1.1 What is it? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 On-line help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Using the Editor to create a new le . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 M-les . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5 Laplace and Inverse Laplace transforms . . . . . . . . . . . . . . . . . . . . . . . 8
1.6 The Matlab ODE solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2 Problem sets 11
2.1 Problem set 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2 Problem set 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.3 Problem set 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4 Problem set 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.5 Problem set 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1 Introduction to Matlab
These notes mostly refer to Matlab under Windows on PC Caledonia. If you would like run
Matlab at home you need to buy the program. There is a free alternative to Matlab called
Octave , which is very similar toMatlab . Most of the programs introduced in this document
(apart from those requiring Symbolic Math Toolbox for Matlab ) will run under Octave with
at most minor modications.
The following notes provide a quick summary of Matlab to allow a quick start. The booklet
An Introduction to Matlab by David F. Griths (downloadable through Vision) provides a
broader introduction to Matlab .
1
real world = outside university
F18XD Matlab 2
Other useful help facilities for Matlab can be found in the Mathematics folder on PC-
Caldonia.
Click on File (at the top left of the Matlab command window) and select New and then
M-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. Select
Save 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 Save
in box: pull down the arrow at its right side until you come to something that starts with
your 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 your
program. It is called myprog.m and it is stored in your home directory (corresponding to
h: in Matlab).
To test this out (and check whether you have saved the le correctly), go back to the
Matlab 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. It
is very important that you learn how to save les before you create anything complicated.
Matrices
Matlab only really deals with one type of object rectangular matrices, whose entries can
either be numbers (real or complex), or text string characters. Matrices with only one row or
column can be treated as vectors, and 11 matrices as scalars. (See Sections 5, 8 and 15 of
An Introduction to Matlab .)
Type the lines
F18XD Matlab 3
x = [-2, 4, -8]
y = [3, 5, 7]
z = [1; 2; 3]
a = 5
A = [-1 0; 3 1]
to create two 13 (row) vectors (x and y ), a column vector (z ), a scalar (a) and a 22 matrix
(A). Note that unlike some programming languages the case of variable names does matter in
Matlab , so that a and A represent dierent quantities. Matrices are usually entered in for
loops ( An Introduction to Matlab Section 18) or using colon notation. Note that ending a
line 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 a
matrix or vector will only accept positive integers as indices, so that B(12,197) is OK, whilst
B(0,1), B(2,-3), or B(1.3,1) are not.
Matrix operations
Most of matrix operations are listed in Section 15 of An Introduction to Matlab . Note that
many 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 . Conrm this
in Matlab with the 22 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 12 and 15.9 of An Introduction to Matlab .
>> A = [-1 0 ; 3 1]
F18XD Matlab 4
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
>> [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 the
corresponding eigenvalues such that A*V = V*D.
Functions
These are introduced in Section 7 and listed in Section 26 of An Introduction to Matlab .
Note that many scalar functions apply entry wise to matrices or vectors. Try out the following
examples (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)
F18XD Matlab 5
sum20 = 0
for i = 1:20
sum20 = sum20 + i
end
(the indentation isn't necessary but makes the code clearer). This code:
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 between
1 and 20, starting with 1 and ending with 20. If a, b and c a:b:c means all
are numbers, then
the 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.
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 18 and 20 deal with for loops and related things in detail.
if . . . else statement
The if statement allows the execution of dierent commands depending on the value of some
logical test.
a = 3;
b = 2;
if (a<b)
j = -1;
else
j = 0;
end
What is the value of j in the above example?
The code below produces a vector v = 1 2 2 2 2 3 3 3 3 3.
v = zeros(1,10);
for i = 1:10
if (i < 2)
v(i) = 1;
elseif (i > 1 && i <= 5)
v(i) = 2;
else
F18XD Matlab 6
v(i) = 3;
end
end
Section 20.2 of An Introduction to Matlab explains the if statement in more detail.
Plotting graphs
The simplest plot command has the form plot(x,y), where x and y are vectors of the same
length, n say. It plots a graph of the points (x1 , y1 ), (x2 , y2 ), . . . , (xn , yn ). For example, type
in 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 13 of An Introduction to Matlab describes how to make multi-plots, 3D plots and how
to 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 collection
of characters surrounded by single quotes. Another example is
st = '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 of
how to use it and a slightly more complicated string expression, type
title(['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 than
one string element is used (typical when mixing words and numbers), then the string elements
to be joined together must be enclosed in square brackets and separated by commas.
1.4 M-les
Matlab can be used in two main ways. You can either type instructions directly at the prompt
or 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 own
language. Typing commands at the prompt is ne if you want to execute single commands, but
errors usually creep into the typing of longer expressions and sequences of operations and it is a
pain having to retype things used over and over again. In general, you should use M-les, and
the mechanism for creating them is described in Section 1.3 above.
There are two dierent kinds of M-les, script les and function les, which act in slightly
dierent ways. Script M-les act as a shorthand for a sequence of Matlab commands and are
a bit easier to use than function M-les. We discuss both types of M-les below, and Sections
10 and 22 of An Introduction to Matlab also describe them in detail.
F18XD Matlab 7
Typing the name S20 at the Matlab prompt will execute the M-le and should result in the
line
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]
It contains an input argument (x), the 4component vector output argument v and a function
statement (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
F18XD Matlab 8
You can use the M-le to create named vectors for example if you type w = mkvec(6) then
you 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:
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 le
mkvec3a.m below:
k = 0:n;
v = x.^k;
len = length(v);
See Section 22 of An Introduction to Matlab for more details.
>> syms t
>> f=t;
>> laplace(f)
ans = 1/s^2
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 Laplace
transforms can use Maple instead. The syntax is quite similar to Matlab . To compute
Laplace transform in Maple we can type
> with(inttrans):
> f:=t:
> laplace(f, t, s);
1
s2
To compute an inverse Laplace transform we type
> with(inttrans):
> f:=1/s^2:
> invlaplace(f, s, t);
t
dx1
= f1 (t, x1 , x2 , x3 , . . . )
dt
dx2
= f2 (t, x1 , x2 , x3 , . . . )
dt
dx3
= f3 (t, x1 , x2 , x3 , . . . )
dt
...
i.e.
dx
= F (t, x).
dt
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 x1 1 1 x1
=
dt x2 1 2 x2
function main
% Use ODE45 to solve
% dx_dt(1) = -1*x(1)-1*x(2)
% dx_dt(2) = 1*x(1) -2*x(2)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rhs function x'=F(t,x)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dx_dt]= F(t,x)
M = [-1,-1; 1,-2];
dx_dt = M*x;
return
F18XD Matlab 11
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.
(d) If A and B are nn matrices, what is the dierence between AB and A. B ? Try
it out for some 22 matrices that you choose yourself.
2. Use the colon notation to generate the vector x = (0.6, 0.7, . . . , 4.4, 4.5).
Use length and sum and see Section 21.2 of An Introduction to Matlab .
(a) Find the vector s whose j th element is the sine of the j th element of x.
(b) Plot vector s against x using the line style stars and put appropriate labels on the
graph.
(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 dened in Matlab more
simply by using the command A = hilb(3).
5. What eect do the commands format short e, format long e and format compact have
on Matlab output ? Try it out by typing pi after the various format commands. (See
help format).
6. Create
7. (a) Use the editor to create a function M-le called anysump.m which takes as input the
positive integer N, and as output the result p of the summation
N
X
p= j 2 .
j=1
(b) Compute from the Matlab command window, the value of the sum for N = 5, 10, 15, 20.
(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 Lecture
notes)
(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 near
where 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, and
outputs the sum
n
X
kr .
k=1
n
X n (n + 1) (2n + 1)
k2 =
6
k=1
11. Plot an (x, y) graph for x [5, 5] when y = sin(x) + 1 x. Use the information from the
graph to help the built-in function fzero nd the root of the equation sin(x) + 1 x = 0.
F18XD Matlab 13
2. (a) Write a function M-le using for loops to dene the N N tridiagonal matrix A and
vector b given by
0 ... 0
. sin(1)
.
. sin(2)
.. .. ..
A= 0 , b= ,
. . . 0
sin(N 1)
..
. sin(N )
0 0
which will work for any integer N 3. Make sure that b is a column vector. The
matrix A is called tridiagonal because all its entries are zero apart from those on or
immediately next to the diagonal.
(c) Use the command eig to nd the eigenvalues and eigenvectors of the matrix A with
N = 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 b
an N vector:
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 of
Ax = b for randomly chosen A and b (rand).
(b) Then write a second M-le for depicting the two resulting times for N = 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
f (xk )
xk+1 = xk for k = 1, 2, 3 . . . ,
f 0 (xk )
F18XD Matlab 14
Step 3 stop when |xk+1 xk | < TOL, where TOL is a small number supplied by the user
or if we reach k = 100 without nding a solution.
(a) Write a function M-le with input: TOL, initial guess x1 and output: the Newton
method approximation of the solution of cos(x) = x, and the number of steps taken
to get there. It will make life easier for you if you write the M-le in such a way that
the 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 fzero rst of all, then apply
using the built-in function
your Newton function to the equation cos(x) = x with TOL= 10
6 and try two
dierent 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 starting
guesses 2 x1 2. Is there a pattern in which starting guesses work and which do
not? (for, if, break).
F18XD Matlab 15
(a) Write a function M-le that takes as input x and h, and outputs the forward and
central approximate derivatives of f (x) = sin1 (x).
(b) Set x = 1/2 and plot the modulus of the error in the results against h for h =
1010 , 109 , . . . , 102 . Which gives better results and why do they stop getting better
as h decreases? Use the loglog function to plot, and label the graph appropriately.
F18XD Matlab 16
Zb N
X
I f (x) dx h f (xj ) IN
a j=1
where the width of the strips is h = (b a)/N and the mid points of the strips are
xj = a + h(j 21 ). The error in the approximation IN is roughly one third of the dierence
between IN/2 and IN .
R2 3
(a) Write an M-le to approximate the integral
1 sin(x ) 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 Logistic
Map. It is dened 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 the
same gure. (subplot).
(c) Try the case = 3.7, N = 100 with x1 = 0.7, 0.7 + 109 , 0.7 + 106 , 0.7 + 103 and
comment 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 the
pattern the solution settles into. (It might help to list the last 10 numbers in the
sequence in each case.)
dy
= f (y, t)
dt
for 0tl subject to the initial condition y(0) = a.
Step 1 Fix a small value h > 0.
Step 2 Set t0 = 0 and tn = tn1 + h.
Step 3 Find an approximation of y step-by-step from the recursion
yn+1 = yn + hf (yn , tn )
(a) Write an M-function with inputs the parameter h and length of the interval l, and
output the two vectors t and y obtained by applying Euler's method to the initial
value problem
dy
= (1 t)y, y(0) = 1.
dt
(for end).
2
(b) The exact solution of this ODE can actually be found analytically, y(t) = ett /2 .
Plot a graph comparing the exact and the approximate solutions for 0 t 5. Use
a blue lled line for the exact solution and a green dashed line for the approximated
one. Label the graph appropriately. (plot).
(c) Use one of the built-in Matlab ODE solvers (e.g., ode15s) to solve the above ODE
and compare the resulting solution to the one obtained by the Euler's method and
to the exact solution.
F18XD Matlab 18
2. Use Matlab (or Maple ) to nd inverse Laplace transforms of the functions from the
Tutorial exercises.
3. Solve the LCR circuit example problem from the Lecture notes using the Matlab built-in
ODE solvers and compare the computed solution to the exact solution from the lecture
notes.
4. Use the Matlab build-in ODE solver to solve the following system of ODEs for t (0, 5)
dx1
= x1 + 2x2 ,
dt
dx2
= 2x1 2x2 ,
dt
x1 (0) = 2 x2 (0) = 1, ,
Compare the computed solution with the exact solution from Section 3.5 of the Lecture
notes.
5. Use the Matlab build-in ODE solver to solve the following system of ODEs for t (0, 5)
dx1
= 4x2 + (t 3) ,
dt
dx2
= x1 ,
dt
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 suciently small , e.g. = 0.01). Compute for dierent
values of and compare the computed solution with the exact solution (cf., Lecture notes
Figure 3.2)
cos (2t) t < 3,
x2 (t) =
cos (2t) + 0.5 sin (2t 6) t 3.