Professional Documents
Culture Documents
Matlab
1
1 2 2 2 6
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
On-line help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using the Editor to create a new le Laplace and Inverse Laplace transforms
M-les . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Problem sets
2.1 2.2 2.3 2.4 2.5 Problem set 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Problem set 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Problem set 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Problem set 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Problem set 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10
10 12 14 15 17
Introduction to
Matlab
Matlab at home you need to buy the program. There is a free alternative to
Octave
Matlab Matlab
under Windows on PC Caledonia. If you would like run . Most of the programs introduced in this document
An Introduction to
broader introduction to
Matlab Matlab
Matlab Matlab
Matlab Octave
called with
is essentially a programming language and is similar to C, Pascal, Fortran and other It also has many built-in functions for nding approximate solutions of
widely-used programming languages. (Technically it is a bit of a mixture between a compiler and an interpreter.) mathematical problems, doing linear algebra etc. and producing good graphs of the results. runs on most standard computer systems (PCs, Macs, Unix workstations etc.) and is widely used in higher education to teach numerical analysis and other topics because easier to learn and to use than most other programming languages. However, once looks and behaves almost the same on each one.
much
Matlab
1 or further study.
both as a quick way to develop and test complex software, and for the facilities provided by the many add-on toolboxes tailored for dierent applications. These toolboxes include nancial modelling, image enhancement, systems control, simulation and optimisation.
Matlab
EPS4 Matlab
help *** in the command window to get information on the command *** or M-le ***.m (here *** stands for any command name e.g. mean, std, sum etc. listed in Section 28 of the Introduction to ). You may also type doc *** in order to get the same
If you know the name of the command you want to nd out about, type
Matlab
Matlab
Matlab
Matlab
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
h:
myprog.m
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
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.
ilaplace
from the
Matlab
laplace()
f (t) = t
we type at the
Matlab
prompt
EPS4 Matlab
F (s) = 1/s2
we type
Maple Maple
Matlab
. To compute
1 s2
To compute an inverse Laplace transform we type
Matrices
either be numbers (real or complex), or text string characters. Matrices with only one row or column can be treated as vectors, and
Matlab
only really deals with one type of object rectangular matrices, whose entries can
An Introduction to
Type the lines
Matlab
11
.)
x y z a A
= = = = =
to create two
y ),
Matlab
loops (
An Introduction to
;
, so that
and
22
matrix
Matlab
represent dierent quantities. Matrices are usually entered in for Section 19) or using colon notation. Note that ending a
B(0,1), B(2,-3),
or
B(1.3,1)
are not.
EPS4 Matlab
Matrix operations
Most of matrix operations are listed in Section 16 of
An Introduction to
.
entry equal to
Matlab
. Note that
A*A
in
Matlab
is the matrix
A2 ,
whilst
A.*A
(i, j )
A(i, j )2 .
Conrm this
with the
22
matrix
below:
0 1
0 1
An Introduction to
Matlab
we can use
0 1
A.
we type
>> A = [-1 0 ; 3 1] A = -1 3 0 1
EPS4 Matlab
0.5547 -0.8321
A*V = V*D.
contains the
Functions
These are introduced in Section 7 and listed in Section 28 of examples (remember that you can nd out what the command
An Introduction to
does by typing
Note that many scalar functions apply entry wise to matrices or vectors. Try out the following
Matlab
***
help ***).
sum20
to zero;
sum20 = sum20 + i.
a, b and c are numbers, then a:b:c means all a+b, a+2b, . . . ending at or just before c. The syntax is first:increment:last. include an increment (e.g. i=1:20 above), then it is assumed to equal 1.
i = 1:20
Type in the following lines to get a better idea of what is going on.
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 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 10 of
An Introduction to
to change the axes scaling and line styles. Axis labels and a title can be added using the
Matlab
ylabel
and
title
ylabel('sin t')
xlabel,
Text strings
The argument of the above
ylabel
num2str,
disp, input
and
error
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.5 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 le (called an M-le) to
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 13 and 21 of a bit easier to use than function M-les. We discuss both types of M-les below, and Sections
Matlab
Matlab
Matlab
's own
An Introduction to
Matlab
Matlab
EPS4 Matlab
.m)
Matlab
S20.m
does what is required. Follow the instructions in Section 1.3 and create this
% 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 line
S20
at the
Matlab
lot 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). Typing
help S20
will print out the lines at the top of the le that start with a
up to the rst line that doesn't start with a anyone else who uses your
Matlab
%.
Matlab
%.
%,
mkvec.m)
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];
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.
It contains an You should get the result
ans = 1 2 4 8
You can use the M-le to create named vectors for example if you type you obtain
then
w = 1
instead. Function M-les can have more than one input argument e.g. the le
36
216 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 %MKVEC3 % %
[v, len] = mkvec3(x,n) 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.
mkvec3a.m
below:
[v, len] = mkvec3a(x,n) 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. not use loops
An Introduction to
Matlab
EPS4 Matlab
The
The Matlab ODE solvers are written to solve systems of DE's of the form
i.e.
There are several built-in ODE solvers from which we can chose, e.g.,
d dt
using the
x1 x2
1 1 1 2
x1 x2
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
EPS4 Matlab
10
2
1.
Problem sets
(a) What is the semi-colon for? (b) Generate the row vector
and
are
nn 22
matrices, what is the dierence between matrices that you choose yourself.
AB
and
A. B ?
Try
2. Use the colon notation to generate the vector (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
An Introduction to
j th
Matlab
3. Generate the vector (a) Find the vector (b) Plot vector graph. See Section 10 of 4.
j th
element of
x.
against
using the line style stars and put appropriate labels on the
An Introduction to
Matlab
(i.e.
Ax = b
\).
Matlab
more
help format).
6. Create (a) a (b) a (c) a
Matlab
99 79 46
format short e, format long e and format compact have pi after the various format commands. (See
Use (eye,
zeros, ones).
EPS4 Matlab
11
7.
(a) Use the editor to create a function M-le called positive integer
N,
p=
j =1
j 2 .
(b) Compute from the Matlab command window, the value of the sum for 8. (a) Follow the examples in Section 10 of
x2
An Introduction to
x = 5 : 0.05 : 5
+x1
Matlab
for the
f (x) =
coordinates.
and
(c) Annotate the graph to show which curve is being depicted. (legend, see the Lecture notes) 9. (a) Follow the examples in Section 10 of
x + x2
An Introduction to
x
g (x) = cos(x)
Matlab
to plot
f (x) =
coordinates.
and
(c) Annotate the graph to show which curve is which and place the text f=g here near where the curves cross. (legend,
text,
10. Write a function M-le that takes as input the positive integer
and number
r,
and
kr .
k=1
Use it to check the identity
k2 =
k=1
for various values of 11. Plot an
n (n + 1) (2n + 1) 6
n. x [5, 5]
when
(x, y )
graph for
y = sin(x) + 1 x.
fzero
sin(x) + 1 x = 0.
EPS4 Matlab
12
tridiagonal matrix
A and
given by
0
. . .
.. A= 0 . . . . 0
matrix
.. . 0 N 3.
is called tridiagonal because all its entries are zero apart from those on or
= 1, = 4, = 1,
nd the 42nd element of the solution command.) (c) Use the command
in the
Ax = b in case N = 199.
of
the case
N = 4,
and
eig to nd N = 5, = = 1, = 2.
vector: Method
with
Ax = b
for
where
is an
N N
matrix and
Matlab
commands
We would like to test which method takes the least cpu time. (a) Write an function M-le where the input is the size
(cputime) in seconds it takes by each of the two methods to compute the solution of
Ax = b
and
b (rand).
(b) Then write a second M-le for depicting the two resulting times for Label the graph appropriately. 4. Newton's method for nding a solution of the equation
Step 1 Make a guess at the solution (call it Step 2 calculate the sequence of values
x1 ), x2 , x3 , . . .
from
xk+1 = xk
f (xk ) f (xk )
for k = 1, 2, 3 . . . ,
EPS4 Matlab
Step 3 stop when
or if we reach
13
where
TOL
a solution.
TOL, initial guess x1 and output: the Newton 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. using the built-in function
fzero rst of all, then apply 6 and try two your Newton function to the equation cos(x) = x with TOL= 10 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).
cos(x) = x
EPS4 Matlab
14
z=
x sech(x2
An Introduction to
[2, 2] [2, 2]
Matlab
x
to produce a mesh
in the
subplot(2,2,1).
and mark
(b) Now produce a contour plot of the function (contour) in it with a star at its maximum. 2. The derivative of a well-behaved function various
subplot(2,2,2)
f (x)
with respect to
can approximated by
f (x + h) f (x) , h
(C) : f (x)
f (x + h) f (x h) . 2h h is usually h
decreases.
The labels F and C stand for forward and central respectively. The number relatively small, and the approximations should, in theory, get better as (a) Write a function M-le that takes as input central approximate derivatives of (b) Set as
x = 1/2
for
h =
1010 , 109 , . . . , 102 . Which gives better results and why do they stop getting better h
decreases? Use the
loglog
EPS4 Matlab
15
axb
is split into
strips of equal width, and the function is assumed to be constant over the strip making it easy to integrate. The contributions from all the strips are added up to give the nal approximation. The approximation formula that results is
I
a
where the width of the strips is
f (x) dx h
j =1
f (xj ) IN
h = (b a)/N and the mid points of the strips are 1 xj = a + h(j 2 ). The error in the approximation IN is roughly one third of the dierence between IN/2 and IN .
(a) Write an M-le to approximate the integral 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 The constant
2 3 1 sin(x ) dx with
xk+1 = xk (1 xk ) for k = 1, 2, . . . with starting 0 < 4 controls the type of behaviour observed.
(controlling parameter),
value
x1 (0, 1).
(number of steps)
x1
(x1 , x2 , . . . , xN ). x1
in four horizontal strips on the
(b) Use this to plot same gure. (c) Try the case
xk vs k for (subplot).
various values of
and
= 3.7, N = 100
with
x1 = 0.7, 0.7 + 109 , 0.7 + 106 , 0.7 + 103 and takes the results to deviate from the x1 = 0.7 case.
with
x1 = 0.7, N = 500
dy = f (y, t) dt
for
0tl
y (0) = a.
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 )
with initial value If
y0 = a.
is suciently small, this often produces a good approximation of the solution to the
EPS4 Matlab
(a) Write an M-function with inputs the parameter
16
l,
and
and
dy = (1 t)y, dt
(for
y (0) = 1.
end).
y (t) = ett /2 . 0 t 5. Use
2
(b) The exact solution of this ODE can actually be found analytically, Plot a graph comparing the exact and the approximate solutions for one. Label the graph appropriately. (plot). (c) Use one of the built-in to the exact solution.
a blue lled line for the exact solution and a green dashed line for the approximated
and compare the resulting solution to the one obtained by the Euler's method and
Matlab
ode15s)
EPS4 Matlab
17
forms from the lecture notes and from the Tutorial exercises. 2. Use
Tutorial exercises.
Maple
3. Solve the LCR circuit example problem from the Lecture notes using the notes. 4. Use the
ODE solvers and compare the computed solution to the exact solution from the lecture
Matlab
built-in
Matlab
t (0, 5)
Matlab
t (0, 5)
t (0, )
, e.g.
= 0.01).
and compare the computed solution with the exact solution (cf., Lecture notes
x2 (t) =
t < 3, t 3.