1 / 45

MATLAB Basics

MATLAB Basics. MATLAB Documentation. Matrix Algebra. http://www.mathworks.com/access/helpdesk/help/techdoc/. http://www.sosmath.com/matrix/matrix.html. What is MATLAB?.

leona
Download Presentation

MATLAB Basics

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

  2. MATLAB Documentation Matrix Algebra http://www.mathworks.com/access/helpdesk/help/techdoc/ http://www.sosmath.com/matrix/matrix.html

  3. 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 acquisition • Modeling, simulation, and prototyping • Data analysis, exploration, and visualization • Scientific and engineering graphics • Application development, including graphical user interface building

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

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

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

  7. Quitting MATLAB • select Exit MATLAB from the File menu in the desktop, or type quit in the Command Window.

  8. MATLAB Desktop

  9. Command Window

  10. Command History

  11. Current Directory Browser

  12. Workspace Browser Command line variables saved in MATLAB workspace • workspace

  13. Window Preferences

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

  15. Using Help • The help command >> help • The help window >> helpwin • The lookfor command >> 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. • ....

  16. Calculations at the Command Line Assigning Variables 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 • a = 2; • b = 5; • a^b • ans = • 32 • x = 5/2*pi; • y = sin(x) • y = • 1 • z = asin(y) • z = • 1.5708 Semicolon suppresses screen output Results assigned to “ans” if name not specified () parentheses for function inputs Numbers stored in double-precision floating point format

  17. Simple Mathematics >> 2 +3 ( 5 ) >> 2 *3 ( 6 ) >> 1/2 ( 0.5000 )>> 2 ^3 ( 8 )>> 0/1 ( 0 )>> 1/0 ( Warning: Divide by zero. Inf )>> 0/0 ( NaN )Up/Down arrow to recall previous commandsOr use Ctrl+C and Ctrl+V to reuse commands

  18. 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 -3floor(x): largest integer not exceeding x, e.g. floor(3.8) returns 3date, exp(x), log(x), log10(x), sqrt(x), abs(x)max(x): maximum element of vector xmin(x): minimum element of vector xmean(x): mean value of elements of vector xsum(x): sum of elements of vector xsize(a): number of rows and columns of matrix a

  19. Some Common Functions rand: random number in the interval [0, 1)realmax: largest positive floating point numberrealmin: smallest positive floating point numberrem(x, y): remainder when x is divided by y, e.g. rem(19,5) returns 4sign(x): returns -1, 0 or 1 depending on whether x is negative, zero or positivesort(x): sort elements of vector x into ascending order (by column if x is a matrix)

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

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

  22. 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]’.

  23. Working with Matrices MATLAB == MATrix LABoratory

  24. The Matrix in MATLAB Columns (n) 1 2 3 4 5 A (2,4) 1 2 Rows (m) 3 4 5 A (17) A = 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25 4 10 1 6 2 8 1.2 9 4 25 7.2 5 7 1 11 0 0.5 4 5 56 Rectangular Matrix: Scalar: 1-by-1 array Vector: m-by-1 array 1-by-n array Matrix: m-by-n array where m, n can be 1, 2, 3, 4, … 23 83 13 0 10

  25. Entering Numeric Arrays Row separator: semicolon (;) Column separator: space / comma (,) • a=[1 2;3 4] • 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 • b = • -2.8000 0 + 2.6458i 10.5000 0 0 • 0 0 0 0 23.0000 Use square brackets [ ] Matrices must be rectangular. (Set undefined elements to zero) Any MATLAB expression can be entered as a matrix element

  26. Entering Numeric Arrays - cont. Scalar expansion • w=[1 2;3 4] + 5 • w = • 6 7 • 8 9 • x = 1:5 • x = • 1 2 3 4 5 • y = 2:-0.5:0 • y = • 2.0000 1.5000 1.0000 0.5000 0 • z = rand(2,4) • z = • 0.9501 0.6068 0.8913 0.4565 • 0.2311 0.4860 0.7621 0.0185 Creating sequences: colon operator (:) Utility functions for creating matrices. (Ref: Utility Commands)

  27. Numerical Array Concatenation - [ ] Use [ ] to combine existing arrays as matrix “elements” Row separator: semicolon (;) Column separator: space / comma (,) • a=[1 2;3 4] • a = • 1 2 • 3 4 • cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] • cat_a = • 1 2 2 4 • 3 4 6 8 • 3 6 4 8 • 9 12 12 16 • 5 10 6 12 • 15 20 18 24 • >> size(cat_a) • ans = • 6 4 Use square brackets [ ] 4*a The resulting matrix must be rectangular.

  28. Array Subscripting / Indexing 1 2 3 4 5 A = 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25 4 10 1 6 2 1 2 3 4 5 8 1.2 9 4 25 A(1:5,5) A(:,5) A(21:25) A(1:end,end) A(:,end) A(21:end)’ 7.2 5 7 1 11 0 0.5 4 5 56 A(3,1) A(3) 23 83 13 0 10 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

  29. Matrix Multiplication • a = [1 2 3 4; 5 6 7 8]; • b = ones(4,3); • c = a*b • c = • 10 10 10 • 26 26 26 [2x4] [4x3] [2x4]*[4x3] [2x3] a(2nd row).b(3rd column) • 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

  30. 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 • Same rules apply for other array operations • a = [1 2 3 4; 5 6 7 8]; • b = [1:4; 1:4]; • c = a.*b • c = • 1 4 9 16 • 5 12 21 32 c(2,4) = a(2,4)*b(2,4)

  31. Deciding with if bal = 15000 * rand;if bal < 5000 rate = 0.09;elseif bal < 10000 rate = 0.12;else rate = 0.15;endnewbal = bal + rate + bal;disp(’New balance is: ’)disp(newbal)

  32. Repeating with for for index = j:k statementsendfor index = j:m:k (m is the increment) statementsend

  33. Square rooting with Newton Method Create a program in newton.m file to calculate the square root of 2%NEWTON Newton Method examplea = 2;x = a/2;for i = 1:6 x = (x+a/x)/2; disp (x)end

  34. Running newton.m >> newton1.5000 1.4167 1.4142 1.4142 1.4142 1.4142>> format long>> newton1.50000000000000 1.41666666666667 1.41421568627451 1.41421356237469 1.41421356237309 1.41421356237309

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

  36. Input / Output Examples fprintf example (io_1.m) balance = 12345;rate = 0.09;interest = rate * balance;balance = balance + interest;fprintf('Interest rate: %6.3f New balance: %8.2f\n', rate, balance);>> io_1Interest rate: 0.090 New balance: 13456.05>>

  37. 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’);

  38. 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_2Enter bank balance: 2000Enter interest rate: 0.08New balance: 2160.00>>

  39. 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: • Plotting multiple lines: plot(xdata, ydata, 'clm') plot(x1, y1, 'clm1', x2, y2, 'clm2', ...)

  40. 2-D Plot – Examples x = 0 : 10y = 2 * xplot (x, y)plot (x, sin(x))x = 0 : 0.1 :10;pauseplot (x, sin(x))plot (x, sin(x)), grid

  41. 2-D Plot – Labels Graphs may be labelled with the following statements:gtext(’text’): writes a string in the graph windowgrid: add/removes grid lines to/from the current graphtext(x, y, ’text’): writes the text at the point specified by x and ytitle(’text’): writes the text as a title on top of the graphxlabel(’text’): labels the x-axisylabel(’text’): labels the y-axis

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

  43. MATLABExercise

More Related