A simple introduction to MATLAB

Download Report

Transcript A simple introduction to MATLAB

A MATLAB tutorial
Bjørn K. Alsberg
Department of Computer Science
University of Wales
Aberystwyth
Introduction
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
What 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.
Starting 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
»
MATLAB is an interpreter
This means you are performing a dialogue with MATLAB:
» (2+5)*10/2
what you type in
ans =
35
»
what MATLAB answers you
MATLAB 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)
Variables
In MATLAB you don’t declare variables. In
general:
variable_name = value
Variables can’t start with a number or names
assigned to the MATLAB language.
a = 12;
c=a-5
c=
7
“Who” 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 = [12;12;89;90];
who
Your variables are:
X
f
qr
“Who” 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
“clear” 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.
Function calls
Most of MATLABs commands are like functions:
OUT = function_name(INPUT);
The ; means that the contents in OUT are not written
to screen.
Vectors - transposing
a1 = [ 1 2 3 ] produce a ROW vector
a2 = [1;2;3] produce a COLUMN vector
' is used to TRANSPOSE:
b1 = a1 '
b1 is now:
1
2
3
Vectors -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 [a;b] is not allowed
Vectors -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)!!!!
Vectors -indexing (1)
The “:”-notation:
from:step:to
6.7:-1.56:-0.11
ans =
6.7000
5.1400
3.5800
2.0200
0.4600
Vectors -indexing (2)
a = [ 5 6 10 11 4]. We want to construct a new
vector from the 3 first elements in a:
b = a(1:3)
If we want the three last elements we need to
know the size of a first:
n = length(a)
b = a(n-2:n)
Matrix - intro
A matrix contains ROWS and COLUMNS:
X=
2
5
2
7
7
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,m]=size(X)
n=3
m=5
Matrix multiplication (1)
Multiplication between
vectors and matrices:
A = [ 1 2 1; 2 9 0; 4 0 3];
v = [0 1 3];
y = A*v'
y=
5
9
9
A=
1
2
1
2
9
0
4
0
3
Matrix multiplication (2)
We could also have written:
y = v*A
It is very useful to remember
that in general a matrix product
has dimensions:
y=
[p x q] = [p x n]*[n x q]
14
9
9
Matrix 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
4.1000
size(A)
ans =
2
4
3.4000
1.2000
0.1000
0.1000
2.2000
0.1000
Matrix multiplication (4)
B is a matrix of random numbers:
B = rand(4,2)
B=
0.2190
0.0470
0.6789
0.6793
0.9347
0.3835
0.5194
0.8310
Matrix multiplication (5)
Now performing the matrix multiplication:
C = A*B
C=
1.8318
1.0900
3.6513
4.4275
Matrix - indexing (0)
A matrix element is extracted by indicating ROW
and COLUMN number(s), e.g.:
C(1,2)
C(4,4)
- first row, second column
- fourth row, fourth column
Matrix - 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
Matrix - 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
Matrix - 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)
Matrix - 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.4*A - 4*B + 100*D
Matrix - 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
The unfolding process operates COLUMNWISE
0
Matrix - folding/unfolding (2)
FOLDING A VECTOR BACK TO A MATRIX:
Xh = reshape(xv,4,3)
1
6
9 10
1
1
85 7
10
45
1
0
Special matrices (1)
X = ones(2,3)
H = eye(4)
X=
H=
1
1
1
1
0
0
0
1
1
1
0
1
0
0
Y = zeros(2,3)
0
0
1
0
Y=0
0
0
0
0
0
1
0
0
0
Special matrices (2)
Q = toeplitz([1 2 3 4])
Q = hankel([1 2 3 4])
Q=
Q=
1
2
3
4
1
2
3
4
2
1
2
3
2
3
4
0
3
2
1
2
3
4
0
0
4
3
2
1
4
0
0
0
Matrix operators (1)
D = diag([1 2 3])
A=
D= 1
0
0
3
5
10
0
2
0
1
0
7
0
0
3
B = fliplr(A)
v = diag(D)
B=
v = [ 1 2 3] '
10
5
3
v = diag(D,1)
7
0
1
v = [0 0] '
Matrix operators (2)
A=
3
1
5
0
10
7
B = flipud(A)
B=
7
10
0
5
rot90 is NOT the
same as transposed:
1
3
B = rot90(A)
B = A’
B=
B=
10
7
3
1
5
0
5
0
3
1
10
7
Matrix operators (3)
.
B =A ^2
The dot notation
means every element
is subjected to a
certain operator. Is
valid for matrices and
vectors:
matrix .operator
(matrix)
B=
9
1
25 100
0
49
or
C = A.*B
C=
27
125
1000
1
0
343
Strings - intro
A string is contained within ' ' characters:
q = ['This is a string vector! '];
Each element in q contains a character:
» q(1:4)
ans =
This
Strings - 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'
Strings - 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']
Strings - conversion (2)
Converting from strings to MATLAB commands:
str =[' Q = A*B'];
eval(str)
Very useful for e.g. multiple matrices:
i = 12
str = ['Q',int2str(i),'= A',int2str(i-1),'*B; ']
eval(str)
Q12 = A11*B;
Strings - 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!
Plots - 2D basic
For simple 2-D plot we use:
6
plot(x) or plot(x,y)
5.5
example:
y = [5 3
5
6
5
4
3];
plot(x) which here is the same
as
plot([1:6],y);
4.5
4
3.5
3
1
1.5
2
2.5
3
3.5
4
4.5
5
5.5
6
Plots - 2D symbols
Scatter 2D plot with various symbols:
1
plot(x,y,’xw’)
0.9
0.8
x = symbol
w = white
Possible symbols in MATLAB 4.2:
. point
o circle
x x-mark
+ plus
- solid
* star
: dotted
-. dashdot
-- dashed
0.7
0.6
0.5
0.4
0.3
0.2
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
Plots - 2D colours
1
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
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
0
5
10
15
20
25
30
Plots - multiple plots
You can plot all the COLUMNS in a
matrix X by:
1
0.9
0.8
X =[0.2190
0.3835
0.5297
0.4175
0.5269
0.9103
0.3282
0.0470
0.5194
0.6711
0.6868
0.0920
0.7622
0.6326];
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
plot(X)
1
2
3
4
5
6
7
Plot - 3D lines
3D plots:
10
plot3(x,y,z)
The command “grid” is
also used
8
6
4
2
0
2
1
1
0.5
0
0
-1
-0.5
-2
-1
Plot - 3D surface
Mesh and contour plots:
3
2
mesh(X)
1
view(angle,elevation)
0
-1
is used to adjust the
viewpoint, or combined:
-2
-3
30
30
20
mesh(X,[angle,elevation])
25
20
15
10
10
5
0
0
Plot - 3D contour
30
Mesh and contour plots:
contour(X,no_lev)
25
20
15
no_lev specifies the number
of contour levels
10
5
5
10
15
20
25
30
Script 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
Script 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
Script 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.
Script 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.
Programming - conditional
statements (1)
IF I == J
NOTE that comparison is
A(I,J) = 2;
==, not =. Other comparison
operators are
ELSEIF ABS(I-J) == 1
>= greater than or equal
A(I,J) = -1;
<= less than or equal
ELSE
~= if different from
A(I,J) = 0;
END
NOTE that IF has no BEGIN
statement only END
Programming - logical
operators (1)
AND, OR and NOT
operators :
& = AND
|
= OR
~ = NOT
IF (A < 1) & (A > 0),
disp(‘ A is between 0 and 1’);
ELSE
disp(‘ A is outside [0,1] ‘);
END;
Programming - logical
operators (2)
The powerful FIND
command:
x = [10 7 1 2 0 990];
idx = find(x < 5 & x > 0)
idx =
3
4
idx = find(x == 1 | x ==7)
idx = 2
3
x = [10 7 1 2 0 990];
y = x<9
y= 0
1
1
1
1
0
1
0
0
y = x<9 & x>1
y= 0
1
x(y)
7
2
0
Programming - FOR loops
The general syntax for FOR loops
FOR variable = expr, statement, ...,
statement END
Double loop example:
FOR i = 1:N,
FOR j = 1:M,
Q(i,j) = 1/(i+j-1);
END
END
Programming - WHILE loops
The general form of a WHILE
statement is:
WHILE variable, statement,
..., statement, END
Example:
WHILE norm(E) > 0,
E = E.*F;
F = A + F/n;
n = n + 1;
END
Debugging
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.
Save (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
Save (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.
Save (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.
load (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.
load (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.
Some 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)
Some 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)
Various numerical methods
Minimize function one variable:
a=fmin('func',x1,x2)
Minimize function of several
variables:a=fmins('func',x0)
Find zero of function in one variable:
a=fzero(‘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)
Management of MATLAB
projects
Commenting your code
Directories
Systematic script files
HTML toolbox
MATLAB 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
MATLAB 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
MATLAB 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
Management of MATLAB - suggested
directory structure
Project
directory
Project specific
m-files +
mat-files
HTML
documents for
each m-file
Project related
documents
Project related
(raw) data files
Figure files
related to
project
MATLAB management systematic script files
Use scripts for experiments (they are
usually unique - not general)
Use a systematic name - you’ll run out
of sensible names
Keep track of systematic script files
(“doit”-files) by a “how”-file.
MATLAB 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
MATLAB 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
MATLAB management - HTML
toolbox (2)
HT provides cross-links between all mfiles 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
MATLAB 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])