Title: A MATLAB tutorial
1A MATLAB tutorial
- Bjørn K. Alsberg
- Department of Computer Science
- University of Wales
- Aberystwyth
2Introduction
- What is MATLAB? General info.
- Manipulation of vectors and matrices
- String manipulation
- Plotting
- Programming (script and function files)
- Simple file input/output
- Some important mathematical functions
- Management of MATLAB projects
3What is MATLAB?
- MATLAB (MATrix LABoratory) is a language for
manipulation of vector and matrix expressions. - MATLAB interprets code and is not compiled (valid
for earlier versions than 5.0 only) - MATLAB provides a powerful on-line graphical
interface to explore the results from
calculations.
4Starting MATLAB
- Find the MATLAB icon and double click
- You will see something like
Commands to get started intro, demo, help
help Commands for more information help,
whatsnew, info, subscribe
5MATLAB is an interpreter
This means you are performing a dialogue with
MATLAB (25)10/2 what you type in ans
35 what MATLAB answers you
6MATLAB as a calculator
All usual numerical operators available
elementary operators - / e.g
899 - 7.88 0.123 math functions abs, cos,
acos, sin, asin, tan, atan, exp, asinh, cosh,
log, log10, sqrt, tanh, conj e.g.
abs(-34.5) , cos(0.7887) (assumes radians),
exp(2.989)
7Variables
In MATLAB you dont declare variables. In
general variable_name value Variables
cant start with a number or names assigned to
the MATLAB language. a 12 c a - 5 c
7
8Who and whos (1)
who/whos are used to display variables and
information about variables currently in working
memory. example qr 99.9 f -190 X
12128990 who Your variables are X
f qr
9Who and whos (2)
whos Name Size Elements Bytes
Density Complex X 4 by 1
4 32 Full No
f 1 by 1 1 8
Full No qr 1 by 1
1 8 Full No
Grand total is 6 elements using 48 bytes
10clear and clc
clear removes all variables from current
memory clc clears the screen and sets the cursor
to the upper left corner of the working window.
11Function calls
Most of MATLABs commands are like functions OUT
function_name(INPUT) The means that the
contents in OUT are not written to screen.
12Vectors - transposing
a1 1 2 3 produce a ROW vector a2 123
produce a COLUMN vector ' is used to
TRANSPOSE b1 a1 ' b1 is now
1 2 3
13Vectors -merging
We can merge vectors. Let a 2 7 5 8 and b
1 1 2. Then c a b will be c 2 7 6 8 1
1 2 The transposed d a b ( here d
c). d a b or ab is not allowed
14Vectors -indexing (0)
Individual elements in a vector are extracted as
follows, e.g. a(1) - the first element in
a a(5) - the fifth element in a Within the
parentheses we have a number (or numbers) that
indicate(s) the element(s) we want to
extract. NOTE!!!! All vector/matrix
indicies start with 1 (not 0)!!!!
15Vectors -indexing (1)
The -notation fromstepto 6.7-1.56-0.11
ans 6.7000 5.1400 3.5800 2.0200
0.4600
16Vectors -indexing (2)
a 5 6 10 11 4. We want to construct a
new vector from the 3 first elements in a b
a(13) If we want the three last elements we
need to know the size of a first n
length(a) b a(n-2n)
17Matrix - intro
A matrix contains ROWS and COLUMNS
2 5 2 7 7 X 1
3 8 9 3 4 1
5 2 4 The dimensions or size of X is
3 ROWS and 5 COLUMNS, i.e. n,msize(X) n 3 m
5
18Matrix multiplication (1)
Multiplication between vectors and matrices A
1 2 1 2 9 0 4 0 3 v 0 1 3 y
Av' y 5 9 9
A 1 2 1 2 9 0
4 0 3
19Matrix multiplication (2)
We could also have written y vA y 14
9 9
It is very useful to remember that in general a
matrix product has dimensions p x q p x
nn x q
20Matrix multiplication (3)
Let us multiply two matrices A and B A 0.5
3.4 0.1 2.2 4.1 1.2 0.1 0.1 A 0.5000
3.4000 0.1000 2.2000 4.1000 1.2000
0.1000 0.1000 size(A) ans 2 4
21Matrix multiplication (4)
B is a matrix of random numbers B rand(4,2) B
0.2190 0.9347 0.0470 0.3835
0.6789 0.5194 0.6793 0.8310
22Matrix multiplication (5)
Now performing the matrix multiplication C
AB C 1.8318 3.6513 1.0900
4.4275
23Matrix - indexing (0)
A matrix element is extracted by indicating ROW
and COLUMN number(s), e.g. C(1,2) -
first row, second column C(4,4) -
fourth row, fourth column
24Matrix - indexing (1)
The indexing for vector can be extended to
matrices k C(,2) k 3.6513
4.4275 is the second column in C. The symbol
means all elements in that index. The second row
in C is r C(2,) r 1.0900 4.4275
25Matrix - indexing (2)
The indexing in MATLAB is very powerful.
The general syntax is Y X(vec1,vec2) where
vec1 and vec2 are vectors containing the the
indices we want to extract from the
matrix X. Example Y X(12 8 1,10 1 2 80
40) size(Y) 4 5
26Matrix - indexing (3)
If you happen to use decimal numbers in the
index vectors, MATLAB automatically performs a
rounding X(1 9,) X(1.2 8.99,) (may
not be true for future versions of MATLAB)
27Matrix - addition
Adding and subtracting matrices and vectors is
easy C A B or C A - B as long as A
and B have the same size. Another example C
12.4A - 4B 100D
28Matrix - folding/unfolding (1)
Unfolding and folding X 1 6 10
9 10 45 1 1 1 85
7 0 X unfolded into a vector xv
(X()) 1 9 1 85 6 10 1
7 10 45 1 0 The unfolding process
operates COLUMNWISE
29Matrix - folding/unfolding (2)
FOLDING A VECTOR BACK TO A MATRIX Xh
reshape(xv,4,3) 1 6 10 9
10 45 1 1 1 85 7
0
30Special matrices (1)
X ones(2,3) X 1 1 1 1 1
1 Y zeros(2,3) Y 0 0 0 0
0 0
H eye(4) H 1 0 0 0 0
1 0 0 0 0 1 0 0
0 0 1
31Special matrices (2)
Q hankel(1 2 3 4) Q 1 2 3
4 2 3 4 0 3 4 0
0 4 0 0 0
Q toeplitz(1 2 3 4) Q 1 2 3
4 2 1 2 3 3 2 1
2 4 3 2 1
32Matrix operators (1)
A 3 5 10 1 0 7 B
fliplr(A) B 10 5 3 7 0 1
D diag(1 2 3) D 1 0 0 0
2 0 0 0 3 v diag(D) v 1
2 3 ' v diag(D,1) v 0 0 '
33Matrix operators (2)
A 3 5 10 1 0 7 B
flipud(A) B 7 0 1 10 5
3
rot90 is NOT the same as transposed B A B
3 1 5 0 10 7
B rot90(A) B 10 7 5
0 3 1
34Matrix operators (3)
B A.2 B 9 25 100 1 0
49 or C A.B C 27 125
1000 1 0 343
The dot notation means every element is subjected
to a certain operator. Is valid for matrices and
vectors matrix .operator (matrix)
35Strings - intro
A string is contained within ' ' characters
q 'This is a string vector! ' Each element
in q contains a character q(14) ans This
36Strings - concatenation
a 'First part ' b 'Second part' c a
b c 'First part Second part' d 'The
',a,'of this string and the ',b d 'The First
part of this string and the Second part'
37Strings - conversion (1)
Converting from integers to strings i
25 str 'She is ',int2str(i),'years
old' Converting from real numbers to strings
k 12.778 str 'The road is
',num2str(k),' miles long'
38Strings - conversion (2)
Converting from strings to MATLAB commands str
' Q AB' eval(str) Very useful for e.g.
multiple matrices i 12 str
'Q',int2str(i),' A',int2str(i-1),'B
' eval(str) Q12 A11B
39Strings - conversion (3)
How do I create a ' in a string when the string
is defined by ' ' ????? Define the string fn
'''' str 'We can now create ',fn,' in a
string! ' We can now create ' in a string!
40Plots - 2D basic
For simple 2-D plot we use plot(x) or
plot(x,y) example y 5 3 6 5
4 3 plot(x) which here is the same as
plot(16,y)
41Plots - 2D symbols
Scatter 2D plot with various symbols
plot(x,y,xw) x symbol w white Possible
symbols in MATLAB 4.2 . point o circle x
x-mark plus - solid star
dotted -. dashdot -- dashed
42Plots - 2D colours
There are several possible colours that can be
used in the plot command y yellow m
magenta c cyan r red
g green b blue w
white k black
43Plots - multiple plots
You can plot all the COLUMNS in a matrix X by X
0.2190 0.0470 0.3835 0.5194
0.5297 0.6711 0.4175 0.6868
0.5269 0.0920 0.9103 0.7622
0.3282 0.6326 plot(X)
44Plot - 3D lines
3D plots plot3(x,y,z) The command grid is
also used
45Plot - 3D surface
Mesh and contour plots mesh(X) view(angle,eleva
tion) is used to adjust the viewpoint, or
combined mesh(X,angle,elevation)
46Plot - 3D contour
Mesh and contour plots contour(X,no_lev) no_lev
specifies the number of contour levels
47Script and function files (1)
Let us say we wrote the following in MATLAB
load data plot(X(1,)) A,D,B svd(X) and
wanted to use these commands often. We can write
the same commands in a any ASCII editor but
without the prompt character. Call this ASCII
file e.g. prog1.m (the extension .m must be
included). Typing prog1 will execute the
program
48Script and function files (2)
Let us include some comment in out program. A
comment line starts with a percentage
character This file describes my experiment
load data plot(X(1,)) A,D,B
svd(X) ---- Typing help prog1 will produce the
n first comment lines in the program This file
describes my experiment
49Script and function files (3)
Functions are declared as follows function
A,Q myfunc(vec1, s,t) A,Q myfunc(vec1,
s,t) This function has inputs vec1, s and t
The output of this function is A and Q The help
command in MATLAB will produce the n first
comment lines after the function declaration for
functions also.
50Script and function files (4)
Remember For MATLAB to recognize your program,
you have to be either - In the current directory
where the function or script is located - or you
must have the home directory of the
function/script in your MATLABPATH. The
MATLABPATH is set by changing a file called
MATLABRC.M in your /MATLAB directory.
51Programming - conditional statements (1)
NOTE that comparison is , not . Other
comparison operators are gt greater than or
equal lt less than or equal if different
from NOTE that IF has no BEGIN statement only END
IF I J A(I,J) 2 ELSEIF ABS(I-J)
1 A(I,J) -1 ELSE A(I,J) 0 END
52Programming - logical operators (1)
AND, OR and NOT operators AND
OR NOT
IF (A lt 1) (A gt 0), disp( A is between 0 and
1) ELSE disp( A is outside 0,1 ) END
53Programming - logical operators (2)
The powerful FIND command x 10 7 1 2 0
990 idx find(x lt 5 x gt 0) idx 3
4 idx find(x 1 x 7) idx 2 3
x 10 7 1 2 0 990 y xlt9 y 0 1 1
1 1 0 y xlt9 xgt1 y 0 1
0 1 0 0 x(y) 7 2
54Programming - FOR loops
The general syntax for FOR loops FOR variable
expr, statement, ..., statement END Double loop
example FOR i 1N, FOR j 1M,
Q(i,j) 1/(ij-1) END END
55Programming - WHILE loops
The general form of a WHILE statement is
WHILE variable, statement, ..., statement,
END Example WHILE norm(E) gt 0, E
E.F F A F/n n n
1 END
56Debugging
There is a debugger in MATLAB, but the two
functions KEYBOARD PAUSE are just as useful.
KEYBOARD stops the program at the location of the
word keyboard. All local variables are
accessible. Type RETURN to get back and run the
program. PAUSE creates a halt in the program
pressing a key will start the program again.
PAUSE(n) pauses the program for n seconds before
continuing.
57Save (1)
The command SAVE saves the current working memory
to a file. save wille save everything in
memory to a file names matlab.mat All mat files
have a special binary format. save mywork will
create a file names mywork.mat
58Save (2)
It is possible to save just selected variables in
memory save filename variable1 variable2
.... Example save mywork X y u1 u2 wxy will
create a file names mywork.mat with the variables
X,y, u1.u2 and wxy only.
59Save (3)
SAVE can also be used to store in ASCII
format SAVE fname X Y Z -ascii uses 8-digit
ASCII form instead of binary. SAVE fname X Y Z
-ascii -double uses 16-digit ASCII form. SAVE
fname X Y Z -ascii -double -tabs delimits with
tabs.
60load (1)
The command LOAD inserts into memory both
MAT-files and ASCII files (with restrictions to
format) load will load in everything to memory
stored in matlab.mat load mywork will load file
mywork.mat. The inclusion of the .mat extension
is optional.
61load (2)
Load can also read ASCII files if they just
contain numbers load tst.dat will create a
variable names tst containing the information
stored in tst. If data is in matrix form (rows
followed by return), the load command will
reconstruct the correct matrix. For more
advanced input/output see fopen, fprintf, fread
etc./ which are C-like commands.
62Some useful linear algebra commands
- Eigenvalue decomposition U,D eig(X)
- Singular value decomposition U,S,V svd(X)
- Inverse of full rank matrices Y inv(X)
- Orthogonalization of a basis set Q orth(A)
- The determinant of a basis set a det(X)
- Pseudoinverse X pinv(A)
- Sum of diagonal elements a trace(X)
- Factors from Gaussian elimination L,U lu(X)
- Generalized eigenvalues AA,BB,Q,Z,V qz(A,B)
- Characteristic polynomial v poly(A)
63Some useful signal processing commands
- Fourier transform f fft(x)
- Inverse Fourier transform x ifft(f)
- 2D Fourier transform F fft2(X)
- Inverse 2D Fourier transform X ifft2(F)
- Convolution c CONV(a,b)
- 2D convolution C CONV(A,B)
- Deconvolution q,r deconv(b,a)
64Various numerical methods
- Minimize function one variable
afmin('func',x1,x2) - Minimize function of several variablesafmins('fu
nc',x0) - Find zero of function in one variable
afzero(func,x) - Solving ordinary differential equations t,y
ode45('yprime', t0, tfinal,y0) - Numerically evaluate integral q
quad8('func',a,b) - Fitting polynomials to data p polyfit(x,y,n)
- Evaluate polynomial y polyval(p,x)
- Convert matrix to sparse A sparse(A)
65Management of MATLAB projects
- Commenting your code
- Directories
- Systematic script files
- HTML toolbox
66MATLAB management - minimum comments
Minimum comment lines describe the INPUT/OUT
parameters function A,B,C boink(Q,a,name)
A,B,C boink(Q,a,name) The n first lines
containing the character will be visible when
we type help boink
67MATLAB management - improved comments
function A,B,C boink(Q,a,name) A,B,C
boink(Q,a,name) INPUT PARAMETERS Q
matrix with values a
vector with values name a string
containing a file name OUTPUT PARAMETERS A
this is the first matrix B
this is the second matrix C
this is the third matrix
68MATLAB management - directories
- If you make general programs - put them in your
own toolbox directories - Keep project specific m-files in directories
related to the project
69Management of MATLAB - suggested directory
structure
70MATLAB management - systematic script files
- Use scripts for experiments (they are usually
unique - not general) - Use a systematic name - youll run out of
sensible names - Keep track of systematic script files
(doit-files) by a how-file.
71MATLAB management - A how file example
HOW FILE FOR WAVELET REGRESSION DOIT
FILES --------------------------------------------
-------------------------------- 1 Wavelet
regression of Data set 1 2 Plotting from
doit1 (Data set 1) 3 Program for constructing
closed concentration system 4 Here we make
concentration matrix 5 Optimization of the
contribution from wavelet scales in wavelet
regression 6 Separate prediction using doit5
results 7 Systematic denoising regression
(Data set 1) 8 Plots from doit7 (Data set
1) 9 Dataset2 systematic PLS regression 10 Plots
from doit9 (Data set 2) 11 Testing the scale
contribution to the y-prediction 12 DS2
Multiresolution loading/score plots for selected
threshold
72MATLAB management - HTML toolbox (1)
- The HTML Toolbox (HT) will simplify the
management of MATLAB projects - The output from HT can also be used as a template
for a documentation of the m-files
73MATLAB management - HTML toolbox (2)
- HT provides cross-links between all m-files in a
directory - HT shows which mat-files are loaded and which
print files are created - HT provides the entire m-code with hyperlinks to
programs used
74MATLAB management - HTML toolbox (3)
- Go to the directory you want to analyse
- Make sure a file named tmp001 is deleted
- Use the program CALLMAK.M
Example callmak(1,1,1 1 1 1 1)