Engr/Math/Physics 25 Chp1 MATLAB OverView: Part-1 Bruce Mayer, PE Licensed Electrical & Mechanical Engineer BMayer@ChabotCollege.edu Engineering/Math/Physics 25: Computational Methods 1 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Learning Goals Turn On MATLAB and use as a calculator Create Basic Cartesian Plots Write and Save simple “Script” Program-files Execute Conditional Statements • IF, THEN, ELSE, >, <, >=, etc. Execute Loop Statements • FOR & WHILE Engineering/Math/Physics 25: Computational Methods 2 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt MATLAB Environment TWO Interaction Modes • INTERACTIVE – Type in the COMMAND WINDOW – Often Called a Command-Window “Session” – Interaction is NOT Saved to Disk Commands (NOT results) Stored in “Command History” Buffer Window • STORED → Two Types – SCRIPT Files – FUNCTION Files Engineering/Math/Physics 25: Computational Methods 3 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt MATLAB Command Window Engineering/Math/Physics 25: Computational Methods 4 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Example Cmd Window Session >> %Use MATLAB As Calculator >> (7+11)*2.5 >> 17*19 ans = ans = 45 323 >> L = 14.4 >> 77/19 -4.3 L = ans = 14.4000 -0.2474 >> W = 13.3 >> 64^(1/3) + 32^0.2 ans = W = 13.3000 6 >> Area = L*W Area = Engineering/Math/Physics 25: Computational Methods 5 191.5200 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Script/Function File Editor Engineering/Math/Physics 25: Computational Methods 6 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Script & Function Files (m-files) SCRIPTS and FUNCTIONS in MATLAB are stored in text files that end with the extension “.m” • These files are called m-files SCRIPTS (a.k.a. “programs”) • Scripts files are useful for automating tasks that may need to be repeated. • They have no input/output parameters • They can (but probably shouldn’t) share variables with the command workspace Engineering/Math/Physics 25: Computational Methods 7 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Script & Function Files (m-files) SCRIPTS (cont.) • Scripts are sequences of interactive statements stored in a file – i.e., They look liked Stored versions of Command Window Sessions FUNCTIONS (a.k.a. “subroutines”) • Function m-files are MATLAB subprograms analogous to FORTRAN Subroutines, or C functions • They communicate with the command window and other functions via a list of INPUT and OUTPUT PARAMETERS or ARGUMENTS Engineering/Math/Physics 25: Computational Methods 8 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Script & Function Files (m-files) FUNCTIONS (cont.) • Functions COMMUNICATE with the COMMAND WINDOW and other m-files via a list of input and output variables • LOCAL variables are variables defined INSIDE the function – They only can be used inside the function in which they reside. • The number of output parameters used when a function is called must match the number of outputs that the function is expected to return Engineering/Math/Physics 25: Computational Methods 9 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Entering Commands & Expressions MATLAB retains your previous keystrokes. Use the up-arrow (↑) key to scroll back through the commands. Press the key (↑) once to see the previous entry, and so on. Use the down-arrow (↓) key to scroll forward. Edit a line using the left (←) & right (→) arrow keys the Backspace key, and the Delete key. Press the Enter key to execute the command Engineering/Math/Physics 25: Computational Methods 10 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Arithmetic Scalar Operations Symbol ^ * / \ + - Operation exponentiation: ab multiplication: ab right division: a/b left division: b/a addition: a + b subtraction: a - b MATLAB a^b a*b a/b a\b a + b a - b LEFT-Division A\b read from Right-to-Left as: “b divided by A” Engineering/Math/Physics 25: Computational Methods 11 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Math Op Precedence (PEMDAS) Precedence Operation First Parentheses, evaluated starting with the innermost pair. Second Exponentiation, evaluated from left to right. Third Multiplication and Division with EQUAL precedence, evaluated from left to right. Fourth Addition and Subtraction with EQUAL precedence, evaluated from left to right. Engineering/Math/Physics 25: Computational Methods 12 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Precedence Examples >> 8+3*5 >> 4^2-12-8/4*2 ans = ans = 23 4 0 >> 8 + (3*5) ans = 23 >>(8 + 3)*5 >> 4^2-12-8/(4*2) ans = 1 3 ans = 55 Engineering/Math/Physics 25: Computational Methods 13 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Precedence Examples cont. >>27^(1/3) + 32^0.2 >> 3*4^2 + 5 ans = 48 ans = 5 53 >>27^1/3 + 32^0.2 >>(3*4)^2 + 5 ans = 144 149 Engineering/Math/Physics 25: Computational Methods 14 3 ans = 9 11 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt “=“ → Assignment Operator Typing x = 3 ASSIGNS the value 3 to the variable x. We can then type x = x + 2. This assigns the value 3 + 2 = 5 to x. But in algebra this implies that 0 = 2. In algebra we can write x+2 = 20, but in MATLAB we cannot. In MATLAB the LEFT side of the = operator MUST be a SINGLE variable. The Right side must be a computable value Engineering/Math/Physics 25: Computational Methods 15 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Work Session Commands Command Description clc Clears the Command window clear Removes all variables from memory clear v1 v2 Removes the variables v1 and v2 from memory exist(‘var’) Determines if a file or variable exists having the name ‘var’ quit Stops MATLAB Engineering/Math/Physics 25: Computational Methods 16 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Work Session Commands cont.1 Command who Description Lists the variables currently in memory Lists the current variables and sizes, whos and indicates if they have imaginary parts. Generates an array having regularly : (Colon) spaced elements , (Comma) Separates elements of an array ; (Semicolon) Suppresses screen printing; also denotes a new row in an array … (Ellipsis) Continues a line Engineering/Math/Physics 25: Computational Methods 17 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt whos on First??? Engineering/Math/Physics 25: Computational Methods 18 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Special VARS & const’s Command Description ans Temporary variable containing the most recent answer eps Specifies the accuracy of floating point precision i,j The imaginary unit (-1) Inf Infinity (unbounded magnitude) Indicates an undefined numerical result; a.k.a., Not a Number pi The number pi (3.14159...) NaN NaN returns the IEEE arithmetic representation for Not-a-Number (NaN). These result from operations which have undefined numerical results;. e.g., try Q = 0/0 Engineering/Math/Physics 25: Computational Methods 19 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt The Complex Plane Im (i or j) F A Bi or F A Bj Re Engineering/Math/Physics 25: Computational Methods 20 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Complex-Number Operations The number c1 = 1 – 2i is entered as: c1 = 12i or c1 = 1-2j An Asterisk is NOT needed between i or j and a NUMBER, although it is required with a VARIABLE, such as c2 = 5 - i*c1. Be careful. The expressions • y = 7/2*i and x = 7/2j give two DIFFERENT results: • y = (7/2)i = 3.5i • and x = 7/(2j) = –3.5j Engineering/Math/Physics 25: Computational Methods 21 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Complex Arithmetic >> Im_Pwr = Z1^3.84 Im_Pwr = -1.6858e+004 -2.5886e+004i >> e_to_Z = exp(Z2) e_to_Z = 6.8518e+006 -2.3163e+007i >> ln_Z = log(Z1) >> Log_Z = log10(Z2) ln_Z = Log_Z = 2.6922 + 1.0769i Engineering/Math/Physics 25: Computational Methods 22 1.2485 + 0.1242i Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Special VARS & const’s Command Description Four decimal digits (the default); format short 13.6745 format long 16 digits; 17.27484029463547 format short e format long e Five digits (four decimals) plus exponent; 6.3792e+03 16 digits (15 decimals) plus exponent; 6.379243784781294e–04 Engineering/Math/Physics 25: Computational Methods 23 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Discrete Math Funtions Command factor(n) gcd(m,n) Description Returns a row vector containing the prime factors of n. Finds the Greatest Common Divisor/Factor of m & n Finds the Least Common Multiple for m&n Returns the factorial of n; i.e., returns factorial(n) n! = 1*2*3…(n-2)*(n-1)*n lcm(m,n) primes(n) Finds all prime numbers less than n isprime(n) Determines if n is a prime number Engineering/Math/Physics 25: Computational Methods 24 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Discrete Math Examples factor777 = factor(777) P93 = primes(93) factor777 = P93 = 3 7 37 Columns 1 through 12 GCF = gcd(1001, 1105) GCF = 13 11 29 Engineering/Math/Physics 25: Computational Methods 25 3 17 37 5 19 7 23 Columns 13 through 24 F7 = factorial(7) F7 = 5040 2 13 31 59 79 41 61 83 43 67 89 47 71 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt 53 73 Arrays An ARRAY is an ORDERED SET of Numbers of with n DIMENSIONS • A regular Number (a SCALAR) is an Array of Dimension ZERO a VECTOR is a 1-Dim Array a MATRIX is an ARRAY of Dim 2 with special properties Engineering/Math/Physics 25: Computational Methods 26 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Arrays in MATLAB The numbers 0, 0.1, 0.2, …, 10 can be assigned to the array variable u by typing • u = [0:0.1:10] To compute w = 5 sin u for u = 0, 0.1, 0.2, 0.3, 0.4,…, 10, the command session is; • >>u = [0:0.1:10]; • >>w = 5*sin(u); The single line, w = 5*sin(u), computed the formula, w = 5 sin(u), 101 times. Engineering/Math/Physics 25: Computational Methods 27 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Array Index >>u(7) ans = 0.6000 >>w(7) ans = 2.8232 Use the LENGTH function to determine how many values are in an array. >>m = length(w) m = 101 Engineering/Math/Physics 25: Computational Methods 28 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Polynomial Roots MATLAB has a Way-Cool Polynomial Root Finder Find the roots of x3 − 7x2 + 40x − 34 = 0 • >>a = [1,-7,40,-34]; • >>roots(a) • ans = • 3.0000 + 5.000i • 3.0000 - 5.000i • 1.0000 The roots are x = 1 and x = 3 ± 5i Engineering/Math/Physics 25: Computational Methods 29 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt 5th Order Polynomial Find the roots of the 5th Order function g y y 9 y 35 y 65 y 64 y 26 0 5 4 3 2 >> r5 = [1,-9,35,-65,64,-26]; >> roots(r5) ans = 3.0000 + 2.0000i 3.0000 - 2.0000i 1.0000 + 1.0000i 1.0000 - 1.0000i The roots of g(y) • y1,2 = 3 ± 2j • y3,4 = 1 ± j • y5 = 1 1.0000 Engineering/Math/Physics 25: Computational Methods 30 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Common Math Functions Fcn MATLAB Fcn ex exp(x) √x sqrt(x) ln x log(x) log10 x log10(x) cos x cos(x) MATLAB sin x sin(x) tan x tan(x) cos-1 x acos(x) sin-1 x asin(x) tan-1 x atan(x) Note that MATLAB Trig functions Operate on RADIANS • Convert using Ratio: -rads per 180° rad rads 180 ; Engineering/Math/Physics 25: Computational Methods 31 e.g., 73 rads 180 1.274 rads Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt The “d” Trig Comands for Degrees >> T1 = sind(77) >> T4 = asind(.497) T1 = T4 = 0.9744 >> T2 = cosd(19) >> T5 = acosd(0.629) T2 = T5 = 0.9455 51.0236 >> T3 = tand(53) >> T6 = atand(1.73) T3 = T6 = 1.3270 Engineering/Math/Physics 25: Computational Methods 32 29.8017 59.9706 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Printing From Command Window - 1 Text to Print Note: MATLAB “Comments” Start with the “%” Sign Engineering/Math/Physics 25: Computational Methods 33 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Printing From Command Window - 2 SELECT Text to Print Engineering/Math/Physics 25: Computational Methods 34 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Printing From Command Window - 3 Send to printer from Print Dialog Box Caveat • In a COMMAND WINDOW session once you Hit Enter () you can NOT Go back to Edit the Text – Can Save your command sequence as an m-file SCRIPT Engineering/Math/Physics 25: Computational Methods 35 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Alternative Cmd Window Printing Perform MATLAB Operation Select Desired Text COPY text to the Windows Paste Buffer PASTE the MATLAB Text Into the Text Processor Print from the Text Processor as Usual Open Text application • MSWord, WordPad, NotePad, etc. Engineering/Math/Physics 25: Computational Methods 36 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt DIARY Function to Record Cmnds Keeping a Session Log → The diary Function • The diary function creates a copy of your session in MATLAB on a disk file, including keyboard input and system responses, but excluding graphics. You can view and edit the resulting text file using any text editor, such as the MATLAB Editor. To create a file on your disk called sept23.out that contains all the functions you enter, as well as output from MATLAB, enter – diary('sept23.out') • To stop recording the session, use – diary('off') • To view the file, run • edit('sept23.out') Engineering/Math/Physics 25: Computational Methods 37 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Command Execution Hierarchy When you type problem1 1. MATLAB first checks to see if problem1 is a variable and if so, displays its value. 2. If not, MATLAB then checks to see if problem1 is one of its own commands, and executes it if it is. 3. If not, MATLAB then looks in the current directory for a file named problem1.m and executes problem1 if it finds it. 4. If not, MATLAB then searches the directories in its search path, in order, for problem1.m and then executes it if found. Engineering/Math/Physics 25: Computational Methods 38 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt System, Directory, File Cmnds Command Description Adds the directory dirname to the addpath dirname search path. cd dirname Changes the current directory to dirname dir Lists all files in the current directory dir dirname Lists all the files in the directory dirname path Displays the MATLAB search path pathtool Starts the Set Path tool HINT: Consider putting ALL your m-files in ONE Folder/Directory Engineering/Math/Physics 25: Computational Methods 39 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Plotting with MATLAB Plot over 573° q p cos p 1.73 ln p 1 QP cosP 1.73 ln P 1 Engineering/Math/Physics 25: Computational Methods 40 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt MATLAB Plotting Commands Command Description Generates a plot of the array y versus plot(x,y) the array x on rectilinear axes title(’text’) Puts text in a title at the top of the plot xlabel(’text’) Adds a text label to the horizontal axis (the abscissa). ylabel(’text’) Adds a text label to the vertical axis (the ordinate). grid Puts grid lines on the plot gtext(’text’) Enables placement of text with the mouse Engineering/Math/Physics 25: Computational Methods 41 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt DeskTop Recovery to UnScramble the DeskTop Engineering/Math/Physics 25: Computational Methods 42 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt DeskTop “Recovery” Engineering/Math/Physics 25: Computational Methods 43 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Example Problem 1-21 Plot This Function T 6 ln t 7e 0.2t • Where – T Temperature (°C) – t time (minutes) • For: 1 t 3 Engineering/Math/Physics 25: Computational Methods 44 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt All Done for Today Tutorial on HomeWork Construction Next Time Engineering/Math/Physics 25: Computational Methods 45 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Engr/Math/Physics 25 Appendix Bruce Mayer, PE Licensed Electrical & Mechanical Engineer BMayer@ChabotCollege.edu Engineering/Math/Physics 25: Computational Methods 46 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Example Demo Session >> %Use MATLAB As Calculator >> (7+11)*2.5 >> 17*19 ans = ans = 45 323 >> L = 14.4 >> 77/19 -4.3 L = ans = 14.4000 -0.2474 >> W = 13.3 >> 64^(1/3) + 32^0.2 ans = W = 13.3000 6 >> Area = L*W Area = Engineering/Math/Physics 25: Computational Methods 47 191.5200 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Prob 1-21 Command Script From the Command Window >> t = [1:0.02:3]; >> T = 6*log(t) - 7*exp(0.2*t); >> plot(t,T), xlabel('time (min)'),ylabel('Temperature (°C)'), title('Problem 1-21'), grid Engineering/Math/Physics 25: Computational Methods 48 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Prob 1-22 Plot Engineering/Math/Physics 25: Computational Methods 49 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Problem 1-22 -6 Temperature (°C) -6.5 -7 -7.5 -8 -8.5 -9 1 1.2 1.4 1.6 1.8 2 2.2 time (min) Engineering/Math/Physics 25: Computational Methods 50 2.4 2.6 2.8 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt 3 System, Directory, File Cmnds Command Description pwd Displays the current directory Changes the current directory to dirname Removes the directory dirname from rmpath dirname the search path. cd dirname Lists the MATLAB-specific files found in the current working directory. Most data what files and other non-MATLAB files are not listed. Use dir to get a list of all files what dirname Lists the MATLAB-specific files in directory dirname Engineering/Math/Physics 25: Computational Methods 51 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt Engineering/Math/Physics 25: Computational Methods 52 Bruce Mayer, PE BMayer@ChabotCollege.edu • ENGR-25_MATLAB_OverView-1.ppt