Matlab Data Book
Matlab Data Book
Tim Love
July 24, 2006
Abstract
This document is aimed at 3rd and 4th years who need to revise matlab for
use in coursework. Many of the examples are taken from Prof J.M.Maciejowski’s
Getting started with Matlab and Dr Paul Smith’s Tutorial Guide to Matlab. most
of the material also applies to using octave. Suggestions and contributions for
this document are welcomed. Mail [email protected].
Contents
1 How to avoid needing this document 2
2 Starting Matlab 3
4 Matrix operations 4
4.1 Creating Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.2 Picking sub-matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.3 Matrix operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.4 Matrix functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
5 Maths 5
5.1 Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
5.2 Numerical Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
5.3 Sparse Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.4 Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
5.5 Symbolic Maths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
7 I/O 7
7.1 Saving and loading data . . . . . . . . . . . . . . . . . . . . . . . . . . 7
7.2 Saving graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
7.3 Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
c
Copyright
2004-6 by T.P.Love. This document may be copied freely for the pur-
poses of education and non-commercial research. Cambridge University Engineer-
ing Department, Cambridge CB2 1PZ, England.
1
8 Graphics 8
8.1 General . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
8.2 3D plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
8.3 Plotting experimental data . . . . . . . . . . . . . . . . . . . . . . . . . 9
8.4 Movies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
10 Programming Constructs 10
10.1 if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
10.2 while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
10.3 for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
10.4 switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
12 Debugging 12
13 Miscellaneous 12
13.1 Stopping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
13.2 Program-generated names and commands . . . . . . . . . . . . . . . 12
13.3 Vectorising . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
13.4 Calling Fortran or C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
• Getting Started1
• Using MATLAB2
• Mathematics3
• Graphics4
• 3-D Visualisation5
• MATLAB Functions Listed by Category6
• MATLAB Functions Listed Alphabetically7
• CUED’s matlab page8
1 http://www.mathworks.com/access/helpdesk/help/techdoc/learn matlab/learn matlab.shtml
2
http://www.mathworks.com/access/helpdesk/help/techdoc/intro tutorial.html
3 http://www.mathworks.com/access/helpdesk/help/techdoc/math anal/math anal.shtml
4 http://www.mathworks.com/access/helpdesk/help/techdoc/creating plots/creating plots.shtml
5 http://www.mathworks.com/access/helpdesk/help/techdoc/visualize/visualize.shtml
6 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/ref.shtml
7 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/refbookl.shtml
8 http://www-h.eng.cam.ac.uk/help/tpl/programs/matlab.html
2
• Reading the online version of this document9 saves you having to type ex-
amples in - you can just copy/paste. You won’t have to type the WWW
addresses either! A PDF version10 is online if you need a paper copy.
2 Starting Matlab
On the teaching system you can type matlab at a Terminal window, or look in the
Programs/ Matlab submenu of the Start menu at the bottom-left of the screen.
Depending on the set-up, you might start with several windows (showing docu-
mentation, etc) or just a command line. This document will focus on command
line operations.
3
• To see which directories are searched, use path. Most of the directories in the
path belong to matlab. The final place it looks is the current directory. If you
have a subdirectory called matlab in your home directory, matlab will look
there before looking in any other directory. The ordering of these directories
matters - if you have a file in the current directory that’s the same name as a
system file, the system’s file will be run rather than yours.
4 Matrix operations
4.1 Creating Matrices
A 1x1 matrix can be created using something like A=7;. A=7:10; creates a matrix
with 4 elements, namely 7, 8, 9 and 10. A=7:0.5:10; creates a matrix with element
values running from 7 to 10 with a step-size of 0.5.
Between [ and ] commas (or spaces) are used to put things in rows, while
semicolons (or line-breaks) put things in columns. So
b = [ 1 3 5; 2 4 6];
creates a matrix with 2 rows and 3 columns.
Matrices can contain strings - e.g. A=’bat’.
There are commands to create particular types of matrices - zeros, ones, eye,
diag, rand, etc.
Note that the normal matrix rules apply, so matrices need to be appropriately
shaped. Using .* (note the extra dot) multiples corresponding elements together.
4
./ and .\ work in a similar way. .^ raises each element to the given power (rather
than the matrix as a whole).
inv inverse
det determinant
trace trace
eig eigenvectors and eigenvalues
rank estimate rank
null calculate a basis for the null space
rref Gaussian elimination on an augmented matrix
lu LU decomposition
qr QR decompostion
svd SVD
pinv Pseudoinverse
rot90 rotation of 90 degrees
triu extract upper triangle
tril extract lower triangle
Some functions are especially useful when used with string matrices. E,g.
A=’abcdefg’
A=fliplr(A)
A=sort(A)
circshift(A,[0 1])
5 Maths
As well as the usual operators there are many functions. See table 3
5
cos cos (angle needs to be in radians)
sin sin (angle needs to be in radians)
tan tan (angle needs to be in radians)
exp exponential
log natural log
log10 base 10 log
sinh hyperbolic sin
cosh hyperbolic cos
tanh hyperbolic tan
acos inverse cos
acosh inverse hyperbolic cos
asin inverse sin
asinh inverse hyperbolic sin
atan inverse tan
atan2 2-argument form of inverse tan
atanh inverse hyperbolic tan
abs absolute value
sign sign (either -1 or +1)
round round to the nearest integer
floor round down to the nearest integer
ceil round up to the nearest integer
fix round towards 0
rem remainder after integer division
sqrt square root
6
5.4 Algebra
Matlab stores polynomials as vectors. For example, 2x 2 − 3x + 1 can be represented
as p=[2 -3 1] and roots found by using roots(p). poly and polyval are also
useful.
• You can display the contents of an array just by typing its name (without
a semi-colon) but that will display the array name too. Particularly if the
array’s a string the disp command is useful - it suppresses the printing of
the array name.
7 I/O
7.1 Saving and loading data
By default matlab saves values into MAT-files with a .mat extension, so save results
Z would save the Z array into a file called results.mat. This array could be
reloaded into matlab by using load results.
You can load files produced by other programs. If a file called data contains “1
2 3” then load data will create a matlab matrix called data which contains those
numbers.
7.3 Printing
Using print or the print menu option will print the current figure to the default
printer. On the teaching system the cuedpr command will do this in a paper-
efficient way.
7
8 Graphics
8.1 General
Before you display graphics you have to calculate coordinates - unlike some other
programs you can’t just print sin(x) and give a range. Typically you’d do some-
thing like the following
x=linspace(0, pi, 100);
y=sin(x);
plot(x,y);
The linspace command creates a vector of 100 elements equally spaced between
0 and pi inclusive.
Once you have a graph it’s easy to add titles - use the menus on the graphics
window or type commands like
title(’Trig’);
xlabel(’Radians’);
ylabel(’Sin’);
You can plot more than one function on a graph. If you use hold on before
doing another plot, the first plot won’t be erased. Alternatively, you can give the
plot command 2 lines at once. The advantage of this approach is that the lines are
automatically drawn in different colours and that legends are easily created - e.g.
x=linspace(0, pi, 100);
y=sin(x);
y2=cos(x);
plot(x,y,x,y2);
legend(’Sin’,’Cos’);
Adding a grid is easy - use grid on. The menu options let you change many
features of graphs, but you can also use the axis command to change many axis
features - range, aspect ratio, etc.
The plot command has many options to control colour, markers, etc. There’s
also scatter, bar, pie, stairs, stem, polar, compass, etc. Type help graph2d or
(if you want to see some graphics!) see the Graphics tutorial11
Note that you can have many figure windows open (read about the figure
command). You can also have many graphs in each figure. The subplot command
creates axes in tiled positions. So for example if you want 3 rows each containing
2 graphs, and you want to plot vector x in the bottom left graph (the 4th graph,
counting left-to-right), you type
subplot(3,2,4);
plot(x);
Use clf to clear the current figure.
8.2 3D plots
There are many 3D options too, but again you still need to calculate all the coordi-
nates.
11
http://www.mathworks.com/access/helpdesk/help/techdoc/creating plots/intro ne.html
8
x=linspace(-1, 1, 10);
y=linspace(-1, 1, 10);
[X, Y]=meshgrid(x,y);
Z= X.^2-Y.^2;
mesh(Z);
The meshgrid command creates 2 2D matrices, each with as many elements as
there are grid-points. The X matrix has the x coordinates and the Y matrix the
y coordinates. Then the z coordinate is calculated for each point and put in a Z
matrix. Instead of mesh, surf could be used to display a facetted surface. Then the
following can be done to add graduated colour and a key.
shading interp;
colorbar
8.4 Movies
To create an animated sequence you first need to draw and save each frame. This
example creates a 16-frame movie then runs it 5 times.
% movie demo
M=moviein(16);
for j = 1:16
plot(fft(eye(j+16)))
M(:,j)= getframe;
end
movie(M,5)
9
lists the properties of the given object, so get(gcf) lists all the properties of the
current figure. You can use set to change the values of these properties once you
know the handle of the object and name of the property. For example, set(gcf,’Color’,’green’)
sets the color of the current figure to green. If you type set(gcf) you get a list of
the properties of the current figure, and alternative settings for these properties.
The axes are children of the figure - and consequently inherit some of the fig-
ure’s properties. If you type get(gcf,’Children’) you’ll get the axes handle,
which you could also get by typing ‘gca’. The axes in turn can have children.
‘set’ is a powerful mechanism. Often matlab has commands that spare you
needing to use set directly, but particularly if you want to retrospectively fix some-
thing, the facility is useful.
10 Programming Constructs
Matlab is a language, not just a calculator. It has the usual programming con-
structs. Both if and while understand all the usual boolean operations (though
note that ~ rather than ! is used for negation - see table 4).
== equal
~= not equal
> greater than
>= greater than or equal
< less than
<= less than or equal
& logical AND
| logical OR
~ logical NOT
10.1 if
if (all(abs(t) >0),
lt = log(t);
else
disp(’There are zeroes in t’);
end
10.2 while
k=1;
while t(k) == 0,
k=k+1;
end
disp(’First nonzero entry in t is’, disp(t(k))
10.3 for
This command is often not needed because matlab functions (sin for example)
often work on whole arrays. The loop below adds an element to back on each
iteration.
10
back=[];
for k=10: -1 : 1,
back=[back,k]
end
10.4 switch
This is like a multiple if statement.
sport=’tennis’;
switch sport
case ’soccer’
disp(’you like soccer’)
case ’tennis’
disp(’you like tennis’)
otherwise
disp(’maybe you like some other sport’)
end
11
cg = cofg([3 1 7],[-2 0 5])
Of course it may be advisable to make your function more sophisticated, for exam-
ple to check whether both input arguments are row vectors, or to make sure that it
will work with either row or column vectors.
It is also possible to pick up subroutines which have been written in other lan-
guages and pre-compiled. See the Interface Guide12 for details.
12 Debugging
• Use size, whos and which to check on variables (or selectively remove semi-
colons from commands so that output isn’t supressed).
• Be careful when choosing variable names
– i begins with the value sqrt(-1) but typing i=7 will change its value.
– If you give a variable the same name as a function odd things can hap-
pen. E.g. the following causes an error on the last line
A=3
size(A)
size = 1
size(A)
13 Miscellaneous
13.1 Stopping
Use CTRL-C to interrupt a command. Use quit to exit from matlab.
12
% A1, A2, A3, and A4 are created and set to 3
for i=1:4
s=sprintf(’A%d= 3’,i);
eval(s);
end;
13.3 Vectorising
for loops are slow and can often be eliminated, though the resulting code may
be less readable. For example, to replace all values < −1 by −1 and all values
> 1 by 1 in a matrix A you can just do A = min(max(M, -1),1). See the Matlab
vectorisation tricks13 page for details.
13
http://www-h.eng.cam.ac.uk/help/tpl/programs/Matlab/tricks.html
14 http://www.mathworks.com/access/helpdesk/help/techdoc/matlab external/matlab external.shtml
13