MATLAB Basics 1 MATLAB Documentation http://www.mathworks.com/access/helpdesk /help/techdoc/ Matrix Algebra http://www.sosmath.com/matrix/matrix.html 2 What is MATLAB? MATLAB (Matrix laboratory) is an interactive software system. It integrates mathematical computing, visualization, and a powerful language to provide a flexible environment for technical computing. Typical uses include • Math and computation • • • Algorithm development • Data analysis, exploration, and visualization • • Scientific and engineering graphics Data acquisition Modeling, simulation, and prototyping Application development, including graphical user interface building 3 The MATLAB Product Family The MathWorks offers a set of integrated products for data analysis, visualization, application development, simulation, design, and code generation. MATLAB is the foundation for all the MathWorks products. Demos: http://www.mathworks.com/products/matlab/demos.html 4 Using MATLAB in CUHK • With Windows Version • With Unix Version • 200 concurrent licenses using throughout the Departments in CUHK • Licenses controlled by a License Server • Used by more than 10 Departments in Engineering and Science Faculties 5 Starting MATLAB • Windows double-click the MATLAB shortcut icon on your Windows desktop. • UNIX type matlab at the operating system prompt. • After starting MATLAB, the MATLAB desktop opens. 6 Quitting MATLAB • select Exit MATLAB from the File menu in the desktop, or type quit in the Command Window. 7 MATLAB Desktop 8 Command Window 9 Command History 10 Current Directory Browser 11 Workspace Browser Command line variables saved in MATLAB workspace »workspace 12 Window Preferences 13 Getting help • MATLAB Documentation • >> helpdesk or doc – Online Reference (HTML / PDF) – Solution Search Engine – Link to The MathWorks (www.mathworks.com) • • FTP site & latest documentation Submit Questions, Bugs & Requests • MATLAB access - MATLAB Digest / Download upgrades 14 Using Help • The help command • The help window • The lookfor command >> help >> helpwin >> lookfor » lookfor example DDEX1 Example 1 for DDE23. DDEX1DE Example of delay differential equations for solving with DDE23. DDEX2 Example 2 for DDE23. ODEEXAMPLES Browse ODE/DAE/BVP/PDE examples. .... » help lookfor LOOKFOR Search all M-files for keyword. LOOKFOR XYZ looks for the string XYZ in the first comment line (the H1 line) of the HELP text in all M-files found on MATLABPATH. For all files in which a match occurs, LOOKFOR displays the H1 line. .... 15 Calculations at the Command Line MATLAB as a calculator » -5/(4.8+5.32)^2 ans = -0.0488 » (3+4i)*(3-4i) ans = 25 » cos(pi/2) ans = 6.1230e-017 » exp(acos(0.3)) ans = 3.5470 Assigning Variables » a = 2; » b = 5; » a^b ans = 32 » x = 5/2*pi; » y = sin(x) Semicolon suppresses screen output Results assigned to “ans” if name not specified y = 1 » z = asin(y) z = () parentheses for function inputs 1.5708 Numbers stored in double-precision floating point format 16 Simple Mathematics >> >> >> >> >> >> >> 2 +3 2 *3 1/2 2 ^3 0/1 1/0 0/0 ( 5 ) ( 6 ) ( 0.5000 ) ( 8 ) ( 0 ) ( Warning: Divide by zero. Inf ) ( NaN ) Up/Down arrow to recall previous commands Or use Ctrl+C and Ctrl+V to reuse commands 17 Some Common Functions cos(x), sin(x), tan(x), asinh(x), atan(x), atanh(x), … ceil(x): smallest integer which exceeds x, e.g. ceil(-3.9) returns -3 floor(x): largest integer not exceeding x, e.g. floor(3.8) returns 3 date, exp(x), log(x), log10(x), sqrt(x), abs(x) max(x): maximum element of vector x min(x): minimum element of vector x mean(x): mean value of elements of vector x sum(x): sum of elements of vector x size(a): number of rows and columns of matrix a 18 Some Common Functions rand: random number in the interval [0, 1) realmax: largest positive floating point number realmin: smallest positive floating point number rem(x, y): remainder when x is divided by y, e.g. rem(19,5) returns 4 sign(x): returns -1, 0 or 1 depending on whether x is negative, zero or positive sort(x): sort elements of vector x into ascending order (by column if x is a matrix) 19 The M-file A Matlab program can be edited and saved (using Notepad) to a file with .m extension. It is also called a M-file, a script file or simply a script. When the name of the file is entered in >>, Matlab (or right-click and then run) carries out each statement in the file as if it were entered at the prompt. You are encouraged to use this method. 20 21 22 Basic Concepts a = 2; b = 7; c = a + b; disp(c) Variables such as a, b and c are called scalars; they are single-valued. MATLAB also handles vectors and matrices, which are the key to many powerful features of the language. 23 Vectors A vector is a special type of matrix, having only one row, or one column. x = [1 3 0 -1 5] a = [5, 6, 8] y = 1:10 (elements are the integers 1, 2, …, 10) z = 1:0.5:4 (elements are the values 1, 1.5, …, 4 in increments of 0.5) x’ is the transpose of x. Or you can do it directly: [1 3 0 -1 5]’. 24 Working with Matrices MATLAB == MATrix LABoratory 25 The Matrix in MATLAB Columns (n) 2 3 4 1 A= 1 2 4 1 8 2 5 6 1 11 6 16 1.2 7 9 12 4 17 25 22 10 2 21 A (2,4) 7.2 3 5 8 7 13 1 18 11 23 A (17) 4 0 4 0.5 9 4 14 5 19 56 24 Rectangular Matrix: 5 23 5 83 10 13 15 0 20 10 25 Scalar: 1-by-1 array Vector: m-by-1 array 1-by-n array Matrix: m-by-n array Rows (m) 3 where m, n can be 1, 2, 3, 4, … 26 Entering Numeric Arrays Row separator: semicolon (;) Column separator: space / comma (,) » a=[1 2;3 4] Use square brackets [ ] a = 1 2 3 4 » b=[-2.8, sqrt(-7), (3+5+6)*3/4] b = -2.8000 0 + 2.6458i 10.5000 » b(2,5) = 23 Matrices must be rectangular. (Set undefined elements to zero) b = -2.8000 0 + 2.6458i 10.5000 0 0 0 0 0 0 23.0000 Any MATLAB expression can be entered as a matrix element 27 Entering Numeric Arrays - cont. Scalar expansion Creating sequences: colon operator (:) » w=[1 2;3 4] + 5 w = 6 7 8 9 » x = 1:5 x = 1 2 » y = 2:-0.5:0 Utility functions for creating matrices. (Ref: Utility Commands) y = 2.0000 1.5000 » z = rand(2,4) 3 4 5 1.0000 0.5000 0.8913 0.7621 0.4565 0.0185 0 z = 0.9501 0.2311 0.6068 0.4860 28 Numerical Array Concatenation - [ ] Use [ ] to combine existing arrays as matrix “elements” Row separator: semicolon (;) Column separator: space / comma (,) The resulting matrix must be rectangular. » a=[1 2;3 4] Use square brackets [ ] a = 1 2 3 4 » cat_a=[a, 2*a; 3*a, cat_a = 1 2 2 3 4 6 3 6 4 9 12 12 5 10 6 15 20 18 4*a; 5*a, 6*a] 4 8 8 16 12 24 4*a >> size(cat_a) ans = 6 4 29 Array Subscripting / Indexing 1 A= A(3,1) A(3) • • • • 4 1 2 2 8 3 7.2 3 4 0 4 5 23 5 1 2 3 4 6 1 11 6 16 1.2 7 9 12 4 17 10 5 2 21 25 22 8 7 13 1 18 11 23 0.5 9 4 14 5 19 56 24 83 10 13 15 0 20 10 25 5 A(1:5,5) A(1:end,end) A(:,5) A(:,end) A(21:25) A(21:end)’ A(4:5,2:3) A([9 14;10 15]) Use () parentheses to specify index colon operator (:) specifies range / ALL [ ] to create matrix of index subscripts ‘end’ specifies maximum index value 30 Matrix Multiplication • • • Inner dimensions must be equal Dimension of resulting matrix = outermost dimensions of multiplied matrices Resulting elements = dot product of the rows of the 1st matrix with the columns of the 2nd matrix » a = [1 2 3 4; 5 6 7 8]; [2x4] » b = ones(4,3); [4x3] » c = a*b [2x4]*[4x3] [2x3] c = 10 26 10 26 10 26 a(2nd row).b(3rd column) 31 Array Multiplication • • • Matrices must have the same dimensions Dimensions of resulting matrix = dimensions of multiplied matrices Resulting elements = product of corresponding elements from the original matrices » a = [1 2 3 4; 5 6 7 8]; » b = [1:4; 1:4]; » c = a.*b c = 1 5 4 12 9 21 16 32 c(2,4) = a(2,4)*b(2,4) Same rules apply for other array operations 32 Deciding with if bal = 15000 * rand; if bal < 5000 rate = 0.09; elseif bal < 10000 rate = 0.12; else rate = 0.15; end newbal = bal + rate + bal; disp(’New balance is: ’) disp(newbal) 33 Repeating with for for index = j:k statements end for index = j:m:k statements end (m is the increment) 34 Square rooting with Newton Method Create a program in newton.m file to calculate the square root of 2 %NEWTON Newton Method example a = 2; x = a/2; for i = 1:6 x = (x+a/x)/2; disp (x) end 35 Running newton.m >> newton 1.5000 1.4167 1.4142 1.4142 1.4142 1.4142 >> format long >> newton 1.50000000000000 1.41666666666667 1.41421568627451 1.41421356237469 1.41421356237309 1.41421356237309 36 Input / Output fprintf formats the output as specified by a format string. fprintf ('format string', list of variables) fprintf ('filename', 'format string' , list of variables) balance = 123.45678901; fprintf('New balance: %8.3f', balance) %8.3f means fixed point over 8 columns altogether (including the decimal point and a possible minus sign), with 3 decimal places (spaces are filled in from the left if necessary). 37 Input / Output Examples fprintf example (io_1.m) balance = 12345; rate = 0.09; interest = rate * balance; balance = balance + interest; fprintf('Interest rate: %6.3f %8.2f\n', rate, balance); >> io_1 Interest rate: 0.090 New balance: New balance: 13456.05 >> 38 Input / Output The input statement gives the user the prompt in the text string and then waits for input from the keyboard. It provides a more flexible way of getting data into a program than by assignment statements which need to be edited each time the data must be changed. It allows you to enter data while a script is running. The general form of the input statement is: variable = input(’prompt’); 39 Input / Output Examples Interactive Input (io_2.m) balance = input('Enter bank balance: '); rate = input('Enter interest rate: '); interest = rate * balance; balance = balance + interest; fprintf('New balance: %8.2f\n', balance); >> io_2 Enter bank balance: 2000 Enter interest rate: 0.08 New balance: 2160.00 >> 40 2-D Plotting • Specify x-data and/or y-data • Specify color, line style and marker symbol (clm), default values used if ‘clm’ not specified) • Syntax: – Plotting single line: plot(xdata, ydata, 'clm') – Plotting multiple lines: plot(x1, y1, 'clm1', x2, y2, 'clm2', ...) 41 2-D Plot – Examples x = 0 : 10 y=2*x plot (x, y) plot (x, sin(x)) x = 0 : 0.1 :10; pause plot (x, sin(x)) plot (x, sin(x)), grid 42 2-D Plot – Labels Graphs may be labelled with the following statements: gtext(’text’): writes a string in the graph window grid: add/removes grid lines to/from the current graph text(x, y, ’text’): writes the text at the point specified by x and y title(’text’): writes the text as a title on top of the graph xlabel(’text’): labels the x-axis ylabel(’text’): labels the y-axis 43 3D Plot - Examples The function plot3 is the 3-D version of plot. The command plot3(x,y,z) draws a 2-D projection of a line in 3-D through the points whose coordinates are the elements of the vectors x, y and z. plot3(rand(1,10), rand(1,10), rand(1,10)) The above command generates 10 random points in 3-D space, and joins them with lines. 44 MATLAB Exercise 45