1 M ATLAB Short Course
History of Calculator 2
3 Introduction to Matlab Matlab is short for Matrix Laboratory Matlab is also a programming language
4 Matlab Basics Basic data type: Matrix A matrix is a two- dimensional array of numbers rows and columns. A vector is a one- dimensional matrix. It may have either one row or one column.
5 Toolboxes Collections of functions to solve problems of several applications. Control Toolbox Neural Network Toolbox Fuzzy Logic Toolbox Genetic Algorithms Toolbox Communication Toolbox …………..
6 Main Working Windows After the “>>” symbol, you can type the commands
7 Display Windows Graphic (Figure) Window Displays plots and graphs Creates response to graphics commands M-file editor/debugger window Create and edit scripts of commands called M-files
8 Getting Help To get help: MATLAB main menu -> Help -> MATLAB Help
9 Getting Help Type one of the following commands in the command window: help – lists all the help topics help topic – provides help for the specified topic help command – provides help for the specified command helpwin – opens a separate help window for navigation Lookfor keyword – search all M-files for keyword Online resource
10 Variables Variable names: Must start with a letter. May contain only letters, digits, and the underscore “_”. MATLAB is case sensitive, for example one & ONE are different variables. MATLAB only recognizes the first 31 characters in a variable name. Assignment statement: Variable = number; >> t=1234 Variable = expression; >>t=a+b
11 Variables Special variables: ans: default variable name for the result. pi: π = …… eps: ε= e-016, smallest value by which two numbers can differ inf: ∞, infinity NAN or nan: not-a-number Commands involving variables: who: lists the names of the defined variables whos: lists the names and sizes of defined variables clear: clears all variables clear name: clears the variable name clc: clears the command window clf: clears the current figure and the graph window
12 Calculations at the Command Line »a = 2; »b = 5; »a^b ans = 32 »x = 5/2*pi; »y = sin(x) y = 1 »z = asin(y) z = »a = 2; »b = 5; »a^b ans = 32 »x = 5/2*pi; »y = sin(x) y = 1 »z = asin(y) z = Results assigned to “ans” if name not specified () parentheses for function inputs Semicolon suppresses screen output MATLAB as a calculator Assigning Variables A Note about Workspace: Numbers stored in double-precision floating point format » -5/( )^2 ans = » (3+4i)*(3-4i) ans = 25 » cos(pi/2) ans = e-017 » exp(acos(0.3)) ans = » -5/( )^2 ans = » (3+4i)*(3-4i) ans = 25 » cos(pi/2) ans = e-017 » exp(acos(0.3)) ans =
13 A = [ ; ] The semi colon separates the rows of a matrix. To print the matrix, type the name. A= Creating Matrices
14 To print the element in the 2 nd row, 3 rd column, type: A(2, 3 ) Matlab prints ans = -25 Accessing Matrix Elements By entering x = A(1,1) + A( 2,3) Matlab returns x = 75
15 To change an entry, enter the new value: A(2,3) = -50 Matlab prints the new matrix A A = Changing Matrix Elements
16 Numerical Array Concatenation »a=[1 2;3 4] a = »cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] cat_a = »a=[1 2;3 4] a = »cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] cat_a = Use [ ] to combine existing arrays as matrix “elements” Row separator: semicolon (;) Column separator: space / comma (,) Use square brackets [ ] 4*a
17 The : operator x = 1 : 7 or x = [ 1 : 7 ] creates the same vector as the command x = [ ] y = 0 : 3 : 12 is the same as y = [ ] y = 0 : 3 : 11 is the same as y = [ ] z = 15 : -4 : 3 is the same as z = [ ] w = 0 : 0.01 : 2 is the same as w = [ ]
18 Deleting Rows and Columns »A=[1 5 9; ; i+1] A = i »A(:,2)=[] A = i »A(2,2)=[] ??? Indexed empty matrix assignment is not allowed. »A=[1 5 9; ; i+1] A = i »A(:,2)=[] A = i »A(2,2)=[] ??? Indexed empty matrix assignment is not allowed.
19 Array Subscripting / Indexing A = A(3,1) A(3) A(1:5,5) A(:,5) A(21:25) A(4:5,2:3) A([9 14;10 15]) A(1:end,end) A(:,end) A(21:end)’
20 Special Matrices and Commands Z = zeros( 4, 5 )Z = K = ones( 4, 5 ) is a matrix of 1’s Id = eye( 4, 5 ) Id =
21 Special Matrices and Commands The transpose operator is ’ transZ = Z’ Z = transZ =
22 >> A = [ ; ] A = >> size(A) a vector of rows and columns in A ans = 2 3 >> length(A) ans = 3 Special Matrices and Commands
23 >> A = [ ; ] A = >> v=diag(A) a vector with the diagonal elements of A v = 100 >> B=diag(v) a matrix with v on the diagonal and 0’s off the diagonal B = Special Matrices and Commands The diag command shows that Matlab commands can depend on the nature of the arguments.
24 Matrix Manipulation Functions zeros : Create an array of all zeros ones : Create an array of all ones eye: Identity Matrix rand: Uniformly distributed random numbers diag: Diagonal matrices and diagonal of a matrix size: Return array dimensions fliplr: Flip matrices left-right flipud: Flip matrices up and down repmat: Replicate and tile a matrix
25 Matrix Manipulation Functions transpose ( ’ ): Transpose matrix rot90: rotate matrix 90 tril: Lower triangular part of a matrix triu: Upper triangular part of a matrix cross: Vector cross product dot: Vector dot product det: Matrix determinant inv: Matrix inverse eig: Evaluate eigenvalues and eigenvectors rank: Rank of matrix
26 Arithmetic Operations A, B are matrices, x is a scalar x*A multiplies each entry of A by x x + A adds x to each entry of A same as x*ones(size(A)) + A x – A same as x*ones(size(A)) – A A + B standard matrix addition A – B standard matrix subtraction
27 Arithmetic Operations (cont.) A*B Standard matrix multiplication cols A = rows B A.*B element-wise multiplication size( A) = size(B) A.\B divide elements of B by those in A A./B divide elements of A by those in B
28 Matrix Multiplication »a = [ ; ]; »b = ones(4,3); »c = a*b c = »a = [ ; ]; »b = ones(4,3); »c = a*b c = [2x4] [4x3] [2x4]*[4x3] [2x3] a(2nd row).b(3rd column) »a = [ ; ]; »b = [1:4; 1:4]; »c = a.*b c = »a = [ ; ]; »b = [1:4; 1:4]; »c = a.*b c = c(2,4) = a(2,4)*b(2,4) Array Multiplication
29 Linear Equations Example: a system of 3 linear equations with 3 unknowns (x 1, x 2, x 3 ) 3 x 1 + 2x 2 - x 3 = 10 - x 1 + 3x 2 + 2x 3 = 5 x 1 - 2x 2 - x 3 = -1 Let: Then, the system can be described as: Ax = b
30 Complex Numbers Matlab works with complex numbers, so sqrt( -3 ) is a valid command. Lowercase i is reserved for the special value sqrt(-1)
31 Special Values pi = Inf = infinity (divide by 0) M = [ pi sqrt(-3); Inf 0] M = i Inf 0
32 Linear Equations Solution by Matrix Inverse: Ax = b A -1 Ax = A -1 b Ax = b MATLAB: >> A = [3 2 -1; ; ]; >> b = [10;5;-1]; >> x = inv(A)*b x = Solution by Matrix Division: Ax = b Can be solved by left division b\A MATLAB: >> A = [3 2 -1; ; ]; >> b = [10;5;-1]; >> x =A \ b x =
33 Example
34 Example
35 Example P=0, Vz=0, My=0, Vy=-1000 lb, Mz=100,000 lb.in
36 Elementary Math Function abs, sign: Absolute value and Signum Function sin, cos, asin, acos…: Triangular functions exp, log, log10: Exponential, Natural and Common (base 10) logarithm ceil, floor: Round toward infinities fix: Round toward zero
37 Elementary Math Function round: Round to the nearest integer gcd: Greatest common devisor lcm: Least common multiple sqrt: Square root function real, imag: Real and Image part of complex rem: Remainder after division
38 Elementary Math Function max, min: Maximum and Minimum of arrays mean, median: Average and Median of arrays std, var: Standard deviation and variance sort: Sort elements in ascending order sum, prod: Summation & Product of Elements trapz: Trapezoidal numerical integration cumsum, cumprod: Cumulative sum, product diff, gradient: Differences and Numerical Gradient
39 Polynomials and Interpolation Polynomials Representing Roots ( >> roots ) Evaluation ( >> polyval ) Derivatives ( >> polyder ) Curve Fitting ( >> polyfit ) Partial Fraction Expansion ( residue ) Interpolation One-Dimensional ( interp1 ) Two-Dimensional ( interp2 )
40 polysam=[ ]; roots(polysam) ans = i i Polyval(polysam,[ ]) ans = polyder(polysam) ans = [r p k]=residue(polysam,[1 2 1]) r = 3 7 p = k = 1 -2 polysam=[ ]; roots(polysam) ans = i i Polyval(polysam,[ ]) ans = polyder(polysam) ans = [r p k]=residue(polysam,[1 2 1]) r = 3 7 p = k = 1 -2 Example
41 x = [0: 0.1: 2.5]; y = erf(x); p = polyfit(x,y,6) p = x = [0: 0.1: 2.5]; y = erf(x); p = polyfit(x,y,6) p = Example interp1(x,y,[ ]) ans = NaN interp1(x,y,[ ]) ans = NaN
42 Logical Operations » Mass = [-2 10 NaN Inf 31]; » each_pos = Mass>=0 each_pos = » all_pos = all(Mass>=0) all_pos = 0 » all_pos = any(Mass>=0) all_pos = 1 » pos_fin = (Mass>=0)&(isfinite(Mass)) pos_fin = » Mass = [-2 10 NaN Inf 31]; » each_pos = Mass>=0 each_pos = » all_pos = all(Mass>=0) all_pos = 0 » all_pos = any(Mass>=0) all_pos = 1 » pos_fin = (Mass>=0)&(isfinite(Mass)) pos_fin = = = equal to > greater than < less than >= Greater or equal <= less or equal ~ not & and | or isfinite(), etc.... all(), any() find Note: 1 = TRUE 0 = FALSE