Title: 28 January 2003, Matlab tutorial: Joanna Waniek jowasoc.soton.ac.uk
1Introduction to Matlab
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
2What is Matlab? What is possible in Matlab?
graphic examples How Matlab works? matrix,
vector scalar syntax important
operators basic commands plot
commands creating a m-file Statistics
in Matlab some basics example Algebraic
operations in Matlab Useful links other
tutorials
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
3What is Matlab?
Matlab is a commercial "Matrix Laboratory"
package which operates as an
interactive programming environment. Matlab is
available for PC's, Macintosh and UNIX
systems. Matlab is well adapted to numerical
experiments. Matlab program and script files
(m-files) always have filenames ending with ".m"
The programming language is
exceptionally straightforward since almost
every data object is assumed to be an
array. Graphical output (figure) is
available to supplement numerical results.
Online help is available from the Matlab prompt
(a double arrow) by typing help.
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
4What kind of graphics is possible in Matlab?
Polar plot t0.012pi
polar(t,abs(sin(2t).cos(2t)))
Line plot x00.055,ysin(x.2),plot(x,y)
Stem plot x 00.14, y
sin(x.2).exp(-x) stem(x,y)
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
5What kind of graphics is possible in Matlab?
Surface plot zpeaks(25), surf(z),
colormap(jet)
Mesh plot zpeaks(25), mesh(z)
Contour plot
zpeaks(25),contour(z,16)
Quiver plot
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
6How to start and quit Matlab?
PC - a double click on the Matlab icon unix
system - setup Matlab (return)
Matlab
On both system leave a Matlab session by typing
quit or by typing exit
at the Matlab prompt.
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
7Using Help in Matlab
Online help is available from the Matlab prompt
(gtgt a double arrow), both generally (listing of
all available commands) gtgt help a long list
of help topics follows and for specific
commands gtgt help fft a help message on the
fft function follows.
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
8Matrix, vector and scalar
Matlab uses variables that are defined to be
matrices. A matrix is a collection of numerical
values that are organized into a specific
configuration of rows and columns. The number of
rows and columns can be any number. A 1 2 3 4
5 6 7 8 A is for example, 2 rows and 4
columns define a 2 x 4 matrix which has 8
elements in total. A scalar is represented by
a 1 x 1 matrix in Matlab a1
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
9Matrix, vector and scalar
A vector of n elements can be represented by a n
x 1 matrix, in which case it is called a column
vector, or a vector can be represented by a 1 x n
matrix, in which case it is called a row vector
of n elements. x 3.5, 33.22, 24.5
x is a row vector or 1 x 3 matrix
x1 2 x1 is
column vector or 4 x 1 matrix 5
3 -1 The matrix name
can be any group of letters and numbers up to 19,
but always beginning with a letter. Matlab is
"case sensitive", that is, it treats the name 'C'
and 'c' as two different variables. Similarly,
'MID' and 'Mid' are treated as two different
variables.
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
10Syntax in Matlab
Colon operator The colon operator ' ' is
understood by Matlab to perform special and
useful operations. For example, if two integer
numbers are separated by a colon, Matlab will
generate all of the integers between these two
integers. a 18 generates the row
vector, a 1 2 3 4 5 6 7 8 . If three
numbers, integer or non-integer, are separated by
two colons, the middle number is interpreted to
be a step" and the first and third are
interpreted to be "limits b 0.0 .2
1.0 generates the row vector b 0.0 .2 .4
.6 .8 1.0
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
11Syntax in Matlab
The colon operator can be used to create a vector
from a matrix. Thus if x 2 6 8
0 1 7 -2 5 -6 The command
y x(,1) creates the column vector y
2 0 -2 The
command z x(1,) creates the row vector
z 2 6 8
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
12Syntax in Matlab
The colon operator is useful in extracting
smaller matrices from larger matrices. If the 4
x 3 matrix c is defined by c -1 0 0
1 1 0 1 -1 0
0 0 2 Then d1
c(,23) creates a matrix for which all elements
of the rows from the 2nd and third columns are
used. The result is a 4 x 2 matrix d1
0 0 1 0 -1 0
0 2
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
13Some basic commands you will need
pwd prints working directory demo
demonstrates what is possible in Matlab who
lists all of the variables in your matlab
workspace whos list the variables and
describes their matrix size clear erases
variables and functions from memory clear x
erases the matrix 'x' from your workspace close
by itself, closes the current figure
window figure creates an empty figure
window hold on holds the current plot and all
axis properties so that subsequent graphing
commands add to the existing graph hold
off sets the next plot property of the current
axes to "replace"
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
14Some basic commands you will need
find find indices of nonzero elements e.g.
d find(xgt100) returns the indices of the vector
x that are greater than 100 break terminate
execution of m-file or WHILE or FOR loop for
repeat statements a specific number of times, the
general form of a FOR statement is
FOR variable expr, statement, ...,
statement END for n1cc/c
magn(n,1)NaNmean(a((n-1)c1nc,1))
end diff difference and approximate derivative
e.g. DIFF(X) for a vector X, is X(2)-X(1)
X(3)-X(2) ... X(n)-X(n-1). NaN the
arithmetic representation for Not-a-Number, a NaN
is obtained as a result of
mathematically undefined operations like 0.0/0.0
INF the arithmetic representation for positive
infinity, a infinity is also produced
by operations like dividing by zero, e.g.
1.0/0.0, or from overflow, e.g. exp(1000).
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
15Some basic commands you will need
save saves all the matrices defined in the
current session into the file,
matlab.mat, located in the current working
directory load loads contents of matlab.mat
into current workspace save filename x y z saves
the matrices x, y and z into the file titled
filename.mat save filename x y z /ascii save the
matrices x, y and z into the file titled
filename.dat load filename loads the contents of
filename into current workspace the file can
be a binary (.mat) file
load filename.dat loads the contents of
filename.dat into the variable filename
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
16Some basic plot commands you will need
Kinds of plots plot(x,y) creates a
Cartesian plot of the vectors x y plot(y)
creates a plot of y vs. the numerical values
of the elements in the y-vector semilogx(x,y)
plots log(x) vs y semilogy(x,y) plots x vs
log(y) loglog(x,y) plots log(x) vs
log(y) polar(theta,r) creates a polar plot of
the vectors r theta where theta is in
radians bar(x) creates a bar
graph of the vector x. (Note also the command
stairs(x)) bar(x,y) creates a
bar-graph of the elements of the vector y,
locating the bars
according to the vector elements of 'x'
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
17Some basic plot commands you will need
Plot description grid creates a
grid on the graphics plot title('text')
places a title at top of graphics
plot xlabel('text') writes 'text' beneath the
x-axis of a plot ylabel('text') writes 'text'
beside the y-axis of a plot text(x,y,'text')
writes 'text' at the location (x,y)
text(x,y,'text','sc') writes 'text' at point x,y
assuming lower left corner is (0,0)
and upper right corner is
(1,1) axis(xmin xmax ymin ymax) sets scaling
for the x- and y-axes on the current plot
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
18How to use a m-file?
files'august2002.dat' ----------------------
--- alength(files(,1)) for i1a,
eval('load c\metdatanode3\',files(i,)) load
the file eval('dd',files(i,110),'')
save in ddl eval('clear
',files(i,110)) end clength(dd(,1))
length of the data-file ldd(1,2)(dd(1,3)/24/1
00)(1c)/24new time plot(l,dd(,15),'ko-') s
et(hd1,'Linewidth',1.2) ylabel('Temperature /
C','Fontsize',10) xlabel('day of
year','Fontsize',10), axis(212 244 10 25),grid
title('aver. dry bulb temp. over last minute')
If you type and save all commands in a file e.g.
temp_plot.m you will be able to create this plot
again! It will look exactly the same! every time
you start temp_plot.m Note, you just wrote your
first program!
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
19Some basic statistics commands you will need
max(x) returns the maximum value of the
elements in a vector or if x is a matrix,
returns a row vector whose elements are
the maximum values from each
respective column of the matrix. min (x)
returns the minimum of x (see max(x) for
details). mean(x) returns the mean value of the
elements of a vector or if x is a matrix, returns
a row vector whose elements are
the mean value of the elements from each
column of the matrix. median(x) same as
mean(x), only returns the median value. sum(x)
returns the sum of the elements of a vector or if
x is a matrix, returns the sum
of the elements from each respective column of
the matrix. prod(x) same as sum(x), only
returns the product of elements.
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
20Some basic statistics commands you will need
std(x) returns the standard deviation of the
elements of a vector or if x is a matrix,
a row vector whose elements are the
standard deviations of each column of
the matrix sort(x) sorts the values in the
vector x or the columns of a matrix and places
them in ascending order. Note that
this command will destroy any association that
may exist between the elements in a
row of matrix x hist(x) plots a histogram of
the elements of vector, x. The bins are scaled
based on the max and min values hist(x,n)
plots a histogram with 'n' bins scaled between
the max and min values of the
elements hist((x(,2)) plots a histogram of the
elements of the 2nd column from the matrix x
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
21If dd(,15) is air temperature in August
2002. max(dd(,15)) gives the maximum
temperature ans 27.1100 mean(dd(,15))
gives the mean temperature ans 17.9839
std(dd(,15)) gives the standard deviation of the
temperature ans 2.7534
kstd(dd(,15))ones(size(dd(,15)))
errorbar(l,dd(,15),k)
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
22Algebraic operations in Matlab
Scalar Calculations addition
- subtraction
multiplication / right division (a/b
means a b) \ left division (a\b
means b a) exponentiation
For example 34 executed
in 'matlab' gives ans12 4/5
gives ans.8
4\5
ans1.25 x pi/2 y sin(x)
y 1
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
23Algebraic operations in Matlab
Matrix Calculations Because matrices are made up
of a number of elements and not a single number
(except for the 1x1 scalar matrix), the ordinary
rules of commutative, associative and
distributive operations in arithmetic do not
always follow. Addition and Subtraction of
Matrices Only matrices of the SAME ORDER can be
added or subtracted. When two matrices of the
same order are added or subtracted in matrix
algebra, the individual elements are added or
subtracted (distributive rule)
A B B A and A - B B -
A If C A B then each element Cij Aij
Bij. For Example A and B are defined as
follows A1 2 3 3 3 3 5 3 1
B2 -3 42 -2 2 0 4 0 Then note
that C A B and C B A
gives C 3 -1 75 1 5 5 7 1
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
24Algebraic operations in Matlab
Multiplication of Matrices is more complex than
arithmetic multiplication because each matrix
contains a number of elements. In matrix
multiplication, the elements of the product, C,
of two matrices AB are calculated from
Cij
Aik Bkj To form this sum, the number of
columns of the first or left matrix (A) must be
equal to the number of rows in the second or
right matrix (B). The resulting product, matrix
C, has an order for which the number of rows
equals the number of rows of the first
(left) matrix (A) and the product (C) has a
number of columns equal to the number of columns
in the second (right) matrix (B). It is
clear that AB IS NOT NECESSARILY EQUAL TO BA!
It is also clear that AB and BA only exist
for square matrices!
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
25Algebraic operations in Matlab
For Example two square 2x2 matrices a 1 2
3 4 b 8 7 6 5 Calling the product c
ab c11 a11b11 a12b21 c12
a11b12 a12b22 c21 a21b11 a22b21
c22 a21b12 a22b22 size(a) returns the
two-element row vector D M, N containing the
number of rows and columns in the
matrix length(a(,1)) returns the length of the
first column
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
26Algebraic operations in Matlab
Array products Recall that addition and
subtraction of matrices involved addition or
subtraction of the individual elements of the
matrices. Sometimes it is desired to simply
multiply or divide each element of an matrix by
the corresponding element of another matrix
'array operations. Array or
element-by-element operations are executed when
the operator is preceded by a '.' (period)
a . b multiplies each element of a by the
respective element of b a ./ b divides
each element of a by the respective element of b
a .\ b divides each element of b by the
respective element of a a . b raise each
element of a by the respective b element
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
27Algebraic operations in Matlab
For example, if matrices G and H are G 1 3
5 2 4 6 H -4 0 3 1 9 8
DG . H -4 0
15
2 36 48
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)
28.
Matlab homepage (news more) http//www.mathwork
s.com/ online tutorials http//www.engin.umich.e
du/group/ctm/ http//www.math.mtu.edu/msgocken/in
tro/intro.html you can find all this
at http//www.soton.ac.uk/jowa/teaching.html
28 January 2003, Matlab tutorial Joanna Waniek
(jowa_at_soc.soton.ac.uk)