1 / 34

CSE123 Introduction to Computing

CSE123 Introduction to Computing. Lecture 2 Introduction to MATLAB. MATLAB. Matlab provides a technical computing environment designed to support the implementation of computational tasks.

luke
Download Presentation

CSE123 Introduction to Computing

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. CSE123 Introduction to Computing Lecture 2 Introduction to MATLAB

  2. MATLAB • Matlab provides a technical computing environment designed to support the implementation ofcomputational tasks. • Matlab is an interactive computing environment that enables numerical computationand data visualization.

  3. MATLAB • Matlab is an effective tool. • very simple numericalor statistical calculations, • some complex statistics, • solve simultaneous equations, • make a graph, orrun and entire simulation program, • Matlab can solve • problemsin applied mathematics, physics, chemistry, engineering, finance – almost any application area that dealswith complex numerical calculations.

  4. MATLAB Running MATLAB • Double-click on the Matlab icon or select Matlab from Start/Programs MATLAB Windows • Command Window • Workspace • Current Directory • Command History

  5. Numbers Matlab represents numbers in two form, fixed point and floating point. Fixed point: Decimal form, with an optional decimal point. For example:2.6349 -381 0.00023 Floating point: Scientific notation, representing m x10e For example: 2.6349 x105 is represented as 2.6349e5 The number has two parts: • mantissa m: fixed point number (signed or unsigned), with an optional decimal point (2.6349in the example above) • exponent e: an integer exponent (signed or unsigned) (5 in the example). • Mantissa and exponent must be separated by the letter e (or E).

  6. Operators “>>”is supplied by Matlab, indicates beginning of the command. ans = following the completion of the command with the Enter key marks the beginning of theanswer.

  7. Operators Try following operations: >> 3 + 5 + 2 >> 4*22 + 6*48 + 2*82 >> 4 * 4 * 4 >> 4^3 >> 56/8 >> 8\56

  8. Precedence of operations (order of evaluation) There are rules about the order of operations 1. Parentheses, innermost first 2. Exponentiation (^), left to right 3. Multiplication (*) and division (/ or \) with equal precedence, left to right 4. Addition (+) and subtraction (−) with equal precedence, left to right When operators in an expression have the same precedence the operations are carried out from left to right. Thus 3 / 4 * 5 is evaluated as ( 3 / 4 ) * 5 and not as 3 / ( 4 * 5 ) .

  9. Precedence of operations (order of evaluation) Examples:

  10. Some built-in functions

  11. Variables and Assignment Statements Assignment statement: variable = number variable = expression variable = input(‘enter a number’) Variable names • Must start with a letter • May consist only of the letters a-z, digits 0-9, and the underscore character (_) • May be as long as you would like, but Matlab only recognizes the first 63 characters • case sensitive: items, Items, itEms, and ITEMS are all different variable names.

  12. Variables and Assignment Statements Example: >> mterm = 60 >> final=80; >> quiz=60 >> grade = 0.5*midterm+0.1*quiz+0.4*final • Variables: mterm,final,quiz,grade • Results displayed and stored by variable name • Semicolon at the end of a line (as in the line >> fianl=80;) tells Matlab to evaluate theline but not to display the results

  13. Variables and Assignment Statements Examples more… >> x=5; >> y=x+5; >> x=2; y is still 10 not 7 you have to run >> y=x+5 again to obtain new value of y. >> z=z+2 is a correct assignment in MATLAB. If you have not supplied a value for xx, Matlab will return a syntax error: >> y=xx+5 ??? Undefined function or variable ’xx’.

  14. Variables and Assignment Statements Examples more… TC=5/9*(TF-32) Sometimes writing an equation in multiple statements makes the equation more understandable numerator = s^2 + 4*s + 13; denominator = s^3 - 2*s^2 + 4*s + 5; H = numerator/denominator;

  15. Example - Solving for quadratic roots 2s2 + 10s + 12 = 0 find roots of the quadratic equation. >> a=2; >> b=10; >> c=12; >> disc = b^2-4*a*c; >> x1 = (-b + sqrt(disc)) /(2*a) >> x2 = (-b - sqrt(disc)) /(2*a) x1 = -2 x2 = -3

  16. input() INPUT Prompt for user input. X=input(‘enter a number’) enter a number2 X = 2 Enter character strings as follows Name=input(‘enter your name :’,‘s’) enter your name :ali Name = ali

  17. disp() DISP There are two general forms of the command disp. • disp(variable): Displays value of variable without displaying the variable name. • disp(string): Displays string by stripping off the single quotes and echoing the charactersbetween the quotes. String: A group of keyboard characters enclosed in single quote marks (’). The quote marksindicate that the enclosed characters are to represent ASCII text. >> temp=78; >> disp(temp); disp(’degrees F’) 78 degrees F

  18. Display Options • There are several commands that can be used to display variables withmore control over the form of the display.

  19. Commands involving variables: who: lists the names of defined variables whos: lists the names and sizes of defined variables clear: clears all variables, resets default values of special variables clear var: clears variable var clc: clears the command window, homes the cursor (moves the prompt to the top line), but doesnot affect variables. clf: clears the current figure and thus clears the graph window. Use commands….

  20. Computational Limitations In Matlab, numbers are typically represented in a floating-point representation conforming to astandard established by the IEEE in 1985. Inthe IEEE double-precision standard used by Matlab, there are 53 bits (approx. 15 significant digits )in the mantissa and 11bits in the exponent (m x 2e), for a total of 64 bits to represent a scalar number. This provides a range ofvalues extending from 10−308 to 10308.

  21. Computational Limitations Two Matlab functions, realmax and realmin, display the largest and the smallest numbers,respectively. >> realmax ans = 1.7977e+308 >> realmin ans = 2.2251e-308

  22. Command reuse and editing • Press the up arrow cursor key (↑) to scrolls backward through previous commands. PressEnter to execute the selected command. • The down arrow cursor key (↓) scrolls forward through commands • The left (←) and right arrow (→) cursor keys move within a command at the Matlabprompt, allowing the command to be edited. • The mouse can also be used to reposition the command cursor, by positioning the mousecursor and pressing the left mouse button.

  23. Command reuse and editing • Other standard editing keys, such as delete Del , backspace BkSp , home Home , and endEnd , perform their commonly assigned tasks. • Once a scrolled or edited command is acceptable, pressing Enter with the cursor anywherein the command tells Matlab to process it. • Escape key Esc erases the current command at the prompt. • Windows copy and paste operations can be used

  24. Getting Help • help – On-line help, display text at command linehelp, by itself, lists all help topics • help topicprovides help for the specified topic • help commandprovides help for the specified command • help help provides information on use of the help command • helpwin – On-line help, separate window for navigation. • helpdesk – Comprehensive hypertext documentation and troubleshooting • help ops: help about operators and special characters • F1 + topic and help tab from File menu.

  25. Interrupting and Terminating Matlab • Ctrl+C: Interrupts (aborts) processing, but doesnot terminate Matlab. • quit: Terminates Matlab • exit: Terminates Matlab • Select Exit under File menu: Terminates Matlab

  26. Files and File Management Matlab provides a group of commands to manage user files • pwd: Print working directory – displays the full path of the present working directory. • cd path: Change to directory (folder) given by path, which can be either a relative or absolute path. • dir : Display the names of the directories (folders) and files in the present working directory. • what: Display the names of the M-files and MAT-files in the current directory. • delete file: Delete file from current directory • type file: Display contents of file (text file only, such as an M-file).

  27. Saving and Restoring Matlab Information It is good engineering practice to keep records of calculations. These records can be used for severalpurposes, including: To revise the calculations at a later time. To prepare a report on the project. Diary Command The diary commands allows you to record all of the input and displayed output from a Matlabinteractive workspace session. The commands include: • diary file: Saves all text from the Matlab session, except for the prompts (>>), as text infile, written to the present working directory. If file is not specified, the information is writtento the file named diary. • diary off: Suspends diary operation. • diary on: Turns diary operation back on. • diary: Toggles diary state

  28. Saving and Restoring Matlab Information Example: >> diary roots >> a=1; >> b=5; >> c=6; >> x = -b/(2*a); >> y = sqrt(b^2-4*a*c)/(2*a); >> s1 = x+y s1 = -2 >> s2 = x-y s2 = -3 The file roots is written in your current working directory. It can be displayed by Matlabcommand type roots.

  29. Storing and Loading Workspace Values save: Stores workspace values (variable names, sizes, and values), in thebinary file matlab.mat in the present working directory save data :Stores all workspace values in the file data.mat save data_1 x y:Stores only the variables x and y in the file data_1.mat load data_1:Loads the values of the workspace values previously stored in the filedata_1.mat

  30. Script M-Files • Group of Matlab commands placed in a text file with a text editor. • Matlab canopen and execute the commands exactly as if they were entered at the Matlab prompt. • The term“script” indicates that Matlab reads from the “script” found in the file. Also called “M-files,” asthe filenames must end with the extension ‘.m’, e.g. example1.m.

  31. Script M-Files Example : Create the file named qroots.m in your present working directory using a text editor: %qroots:Quadratic root finding scriptformat compact; a=1; b=5; c=6; x = -b/(2*a); y=sqrt(b^2-4*a*c)/(2*a); s1 = x+y s2 = x-y To execute the script M-file, simply type the name of the script file qroots at the Matlab prompt: >> qroots a = 1 b = 5 c = 43 6 s1 = -2 s2 = -3

  32. Effective Use of Script Files 1. Thename must begin with a letter and may include digits and the underscore character. 2. Do not give a script file the same name as a variable it computes 3. Do not give a script file the same name as a Matlab command or function. To check existence of command, type exist(’rqroot’). This command returns one of the following values: 0 ifrqroot does not exist 1 ifrqroot is a variable in the workspace 2 ifrqroot is an M-file or a file of unknown type in the Matlab search path ….

  33. Effective Use of Script Files 4. As in interactive mode, all variables created by a script file are defined as variables in theworkspace. After script execution, you can type who or whos to display information aboutthe names, data types and sizes of these variables. 5. You can use the type command to display an M-file without opening it with a text editor. For example, to view the file rqroot.m, the command is type rqroot.

  34. MatlabSearch Path,Path Management Matlab search path: Ordered list of directories that Matlab searches to find script and functionM-files stored on disk. Commands to manage this search path: matlabpath: Display search path. addpath dir: Add directory dir to beginning of matlabpath. If you create a directory to store yourscript and function M-files, you will want to add this directory to the search path. rmpath dir: Remove directory dir from the matlabpath.

More Related