740 likes | 776 Views
A MATLAB tutorial. B j ø 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
E N D
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: 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,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 y = 14 9 9 It is very useful to remember that in general a matrix product has dimensions: [p x q] = [p x n]*[n x q]
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 3.4000 0.1000 2.2000 4.1000 1.2000 0.1000 0.1000 size(A) ans = 2 4
Matrix 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
Matrix multiplication (5) Now performing the matrix multiplication: C = A*B C = 1.8318 3.6513 1.0900 4.4275
Matrix - 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
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 0 The unfolding process operates COLUMNWISE
Matrix - 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
Special 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
Special matrices (2) Q = toeplitz([1 2 3 4]) Q = 1 2 3 4 2 1 2 3 3 2 1 2 4 3 2 1 Q = hankel([1 2 3 4]) Q = 1 2 3 4 2 3 4 0 3 4 0 0 4 0 0 0
Matrix 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] '
Matrix 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
Matrix 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)
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: plot(x) or plot(x,y) example: y = [5 3 6 5 4 3]; plot(x) which here is the same as plot([1:6],y);
Plots - 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
Plots - 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
Plots - 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)
Plot - 3D lines 3D plots: plot3(x,y,z) The command “grid” is also used
Plot - 3D surface Mesh and contour plots: mesh(X) view(angle,elevation) is used to adjust the viewpoint, or combined: mesh(X,[angle,elevation])
Plot - 3D contour Mesh and contour plots: contour(X,no_lev) no_lev specifies the number of contour levels
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.