Transcript of "28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc ..."
1.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) Introduction to Matlab
2.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) What 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
3.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) What 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 .
4.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) What kind of graphics is possible in Matlab ? Polar plot: t=0:.01:2*pi; polar(t,abs(sin(2*t).*cos(2*t))); Line plot: x=0:0.05:5;,y=sin(x.^2);,plot(x,y); Stem plot: x = 0:0.1:4;, y = sin(x.^2).*exp(-x); stem(x,y)
5.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) What kind of graphics is possible in Matlab ? Mesh plot: z=peaks(25);, mesh(z); Surface plot: z=peaks(25);, surf(z);, colormap(jet); Contour plot: z=peaks(25);,contour(z,16); Quiver plot:
6.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) How to start and quit Matlab ? On both system leave a Matlab session by typing : quit or by typing exit at the Matlab prompt. PC - a double click on the Matlab icon unix system - setup Matlab (return) Matlab
7.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) Using Help in Matlab Online help is available from the Matlab prompt ( >> a double arrow), both generally (listing of all available commands): >> help [a long list of help topics follows] and for specific commands: >> help fft [a help message on the fft function follows].
8.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) Matrix, 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 : a=1;
9.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) 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. Matrix, vector and scalar:
10.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) 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 = 1:8 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 ] Syntax in Matlab :
11.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) 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 ] Syntax in Matlab :
12.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) 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(:,2:3) 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 ] Syntax in Matlab :
13.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) Some 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"
14.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) Some basic commands you will need: find find indices of nonzero elements e.g.: d = find(x>100) 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 n=1:cc/c; magn(n,1)=NaNmean(a((n-1)*c+1:n*c,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).
15.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) Some 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
16.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) Some 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'
17.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) 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 Some basic plot commands you will need:
18.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) files=[ 'august2002.dat' ]; % ------------------------- a=length(files(:,1)); for i=1:a, eval([ 'load c:metdatanode3' ,files(i,:)]) % load the file eval([ 'dd=' ,files(i,1:10), ';' ]) % save in ddl eval([ 'clear ' ,files(i,1:10)]) end c=length(dd(:,1)); %length of the data-file l=dd(1,2)+(dd(1,3)/24/100)+(1:c)/24; %new time plot(l,dd(:,15), 'ko-' ); set(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! How to use a m-file ?
19.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) 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. Some basic statistics commands you will need:
20.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) 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 Some basic statistics commands you will need:
21.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) If 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 » k=std(dd(:,15))*ones(size(dd(:,15))); » errorbar(l,dd(:,15),k) »
22.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) Algebraic operations in Matlab: Scalar Calculations: + addition - subtraction * multiplication / right division (a/b means a ÷ b) left division (a means b ÷ a) ^ exponentiation For example 3*4 executed in 'matlab' gives ans=12 4/5 gives ans=.8 45 ans=1.25 x = pi/2; y = sin(x) y = 1
23.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) Algebraic 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: A=[1 2 3; 3 3 3; 5 3 1] B=[2 -3 4;2 -2 2; 0 4 0] Then note that C = A + B and C = B + A gives C =[ 3 -1 7;5 1 5; 5 7 1]
24.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) Algebraic 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 A*B 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 A*B IS NOT NECESSARILY EQUAL TO B*A! It is also clear that A*B and B*A only exist for square matrices!
25.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) For Example: two square 2x2 matrices a = [ 1 2; 3 4]; b = [ 8 7; 6 5]; Calling the product c = a*b c11 = a11*b11 + a12*b21 c12 = a11*b12 + a12*b22 c21 = a21*b11 + a22*b21 c22 = a21*b12 + a22*b22 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 Algebraic operations in Matlab:
26.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) Algebraic 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
27.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) For example , if matrices G and H are G = [ 1 3 5; 2 4 6]; H = [-4 0 3; 1 9 8]; D=G .* H = [ -4 0 15 2 36 48 ] Algebraic operations in Matlab:
28.
28 January 2003, Matlab tutorial: Joanna Waniek (jowa@soc.soton.ac.uk) Matlab homepage (news & more): http://www.mathworks.com/ online tutorials: http://www.engin.umich.edu/group/ctm/ http://www.math.mtu.edu/~msgocken/intro/intro.html you can find all this at: http://www.soton.ac.uk/~jowa/teaching.html … .
A particular slide catching your eye?
Clipping is a handy way to collect important slides you want to go back to later.
Be the first to comment