1 / 74

A MATLAB tutorial

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

chogan
Download Presentation

A MATLAB tutorial

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. A MATLAB tutorial Bjørn K. Alsberg Department of Computer Science University of Wales Aberystwyth

  2. 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

  3. 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.

  4. 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 »

  5. 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 »

  6. 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)

  7. 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

  8. “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

  9. “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

  10. “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.

  11. 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.

  12. 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

  13. 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

  14. 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)!!!!

  15. 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

  16. 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)

  17. 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

  18. 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

  19. 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]

  20. 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

  21. 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

  22. Matrix multiplication (5) Now performing the matrix multiplication: C = A*B C = 1.8318 3.6513 1.0900 4.4275

  23. 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

  24. 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

  25. 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

  26. 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)

  27. 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

  28. 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

  29. 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

  30. 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

  31. 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

  32. 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] '

  33. 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

  34. 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)

  35. 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

  36. 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'

  37. 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']

  38. 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;

  39. 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!

  40. 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);

  41. 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

  42. 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

  43. 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)

  44. Plot - 3D lines 3D plots: plot3(x,y,z) The command “grid” is also used

  45. Plot - 3D surface Mesh and contour plots: mesh(X) view(angle,elevation) is used to adjust the viewpoint, or combined: mesh(X,[angle,elevation])

  46. Plot - 3D contour Mesh and contour plots: contour(X,no_lev) no_lev specifies the number of contour levels

  47. 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

  48. 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

  49. 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.

  50. 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.

More Related