Computing for Engineers
Computing for Engineers ENGR 1731
Popular in Course
Mr. Durward Gleason
verified elite notetaker
Popular in General Engineering
verified elite notetaker
This 43 page Class Notes was uploaded by Mrs. Alaina Hermiston on Monday October 12, 2015. The Class Notes belongs to ENGR 1731 at Georgia Southern University taught by Maria Alba-Flores in Fall. Since its upload, it has received 71 views. For similar materials see /class/222069/engr-1731-georgia-southern-university in General Engineering at Georgia Southern University.
Reviews for Computing for Engineers
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 10/12/15
ENGR 1731 Computing for Engineers Lecture 5 Representation in MATLAB Data Types and Variables Prof AlbaFlores I ll llllllllllllllllllllllllllllllllll Data Types Numeric Variable V Integer Signed Unsigned Real or Floating Point quot Standard notation Scientific notation Valiables in MA I39LRB 1272009 DdtaTyiae s 39 ln MATLABrwe can represent t three types of data in our programs 7 7 l 39 w Numerical i Characters or Alphanu merical Logical ammi m a lllllllllll Data Types Alphanumerical or Character Char V String w Logical Variables In MATLAB we have two main kinds of numerical variables Scalars Single Valued Variables Arra s quot actors Collection ofvalues ofthe same type assigned to av ria Malrixes Multi dimensional collection ofvalues or collection of arrays assigned to a var39a le 1272009 Scalar Examples I r i Vectors mtg r rumba I j A1123 45 67 89 av j v 39 B 23 57 93 15 Temperature 415 l Averageisxxeed 39 eel numb Notauon 37e5 amnnm umvmm l Exam pie 3 for ang es cum 1 Huang 2 Call the vector DEGREES Write a Matlab instriiction that will generate a vector in degrees 39om 0 3 to 36 n 12 n u Columns 23 mmugn 33 DEGREES0136 nanms 331 hmugh 341 Culmns 342 through 5 1 u cum 5 through 3e gtgt DIGPIE5 D 5 35o What will the following instruction do ms i Columns 1 mougn 11 V u 5 1D 15 DEGREES 0 5 36 cum u mougn zz 55 so 55 Calms 23 mmgn 33 no 115 12m 125 Columns u mean u 155 u 175 lea Column 45 mum 55 m 25 12m 235 Colinms 55 mam E5 15 250 255 290 Columns 5 through 7 Mo Ms To generate a vectorwith the equivalent angles in RADIANS we have RADIANS DEGREES pi I180 Matrixes oz157908 884689 Z 1 5 7 39 0 6 6 8 25 78 8912 86 41 88 94 82 25 78 89 12 86 41 88 94 82 Floating Point Numbers A oating point number is a value that has a decimal point that separates the integer part from the fraction part of the number 39 FPN are used to represent any real number that include but is not limited to positives and negatives integers and rational numbers like 70 The position ofthe decimal can be at any digit oating 39 1 1272009 ma um um m um us 1 w 4 Lama mm Luau man 1 m um mm mm 5119 mm mm 5x 5nn gain Integer numbers are values that do not have a decimal point and are the simplest values that we can assign to a variable and they can have be positive or negativequot values Examples A 3 B3567 Floating Point Notation A 133445 B 643098 u c Compute Limitations Whenever we use integers or oating numbers in a computer we need to be aware that because there is a max 39 um number of digits that a computer can handle ata time this will reduce the precision of the result and limit the size of the values that can be represented in the operations 7 Precision Errors Examples gtgt 0420540 8 ans 13878e 0139I gtgt 008O42 5 s 0 gtgt sin pi 39 an 12246e 016 Letter 39 a Name 39 Mary Lis Peter john 1272009 Maximum and Minimum Values gtgt intmax LLm pc integer ans 214748364 gtgtintmin quot39u Minimum 39 integer ans Zl4748 gtgt realmax 39Iazumum posmve re a1 ans 7977e308 gtgt realmin quota Mi mum neauve real numb er ans 22251e3 innun ride gammsanm umvmm Chalacters and Suing Sometimes it is necessaryvto represent non numerical information such as alphabet letters and names In MATLAB a variable used to represent a character or String of characters is identified by enclosing the characters by apostrophes gt Logic Variables Besides the use of numerical and character values we can assign to variable alogic value t V Logic values can have only two possible va ues quot The two values can be expressed either in Binary 0 I or Boolean TrueLFalse form ENGR 1731 Computing for Engineers Georgia Southern University Mechanical and Electrical Engineering Teclinolo gy Spring 2009 Lecture 2 Introduction Prof AlbaFlores Introduction 1 E Programmable Devices Programmable Devices cont max ii i m mm 1731 How important is computer programming to your career mica l73l Some Computer Programming Languages Software Packages applications 39 Auto CAD Vector Works LabVieW Mathematica Excel Matlab FronLPage may 1731 Some Computer Programming Languagescont Highlevel Languages C Fortran 39 basic Python Matlab Mathematica L39NGEmt 7 Some Computer Programming Languagescont Lowrlevel Languages gt Assembly Language gt Machine Language mean a ProgrammerComputer Interaction Programmer Computer High Level Language Translator Machine L guage Fonran Binary Basic man a Language Translation Hierarchy Assembler Language Interpre er Machine camper Language Program Program Language Binary r Ido code mbler Fonran quot Matlab chvszi in High Level Languages Main Characteristics Instructions easy for the programmer to understand Instruction Set independent ofthe machine where the program is running Programs are easy to debug An instruction line in highlevel language is translated into several instructions ofmachine code Code produced by translator is not optimum EVEkHl u Low Level Languages Main Characteristics Instructions difficult for the programmer to understand Instruction Set dependent ofthe machine where the program is running Programs are di icult to debug An instruction line in lowlevel language is translated into one or few lines ofmachine co e Code produced by translator is more e icient maxim n ENGR 1731 Computing for Engineers Georgia Southern University Mechanical and Electrical Engineering Technology Spring 2009 Properties of r in r Matrix Product Complex Numbers in Matlab Prof AlbaFlores METEET Dept Properties of Ordinary Matrix Product 4272009 Properties of Ordinary Matrix Product Consider three matrices A B and C Assume that the matrices dimensions meet the condition to perform ordinary matrix product Matrix Multiplication is not commutative A B 2 B A Matrix multiplication is associative ABC AB C Matrix multiplication is distributive AB C AB AC A BC AC BC Properties of Ordinarv Matrix Product cont Multiplication involving a scalar Consider A and B are matrices and w is a scalar then wAB wA B AwB AwB AB w ABw 4272009 Matrix Inverse The inverse ofa square matrix A sometimes called a reciprocal matrix isa matrix A 1 suc t at A A 1 I where I is the Identity Matrix The identity matrix or unit matrix of size n is the nbyn square matrix with ones on the main diagonal and zeros elsewhere Example for n 3 the identity matrix is l 0 U I g 7 J l 0 0 l 1 0 0 J 0 l 0 0 0 0 1 0 0 0 0 1 In Matlab you can generate an Identity Matrix usingthe function eye Example gtgt Meye 5 M OOOOH ooowo oowoo owooo HOOOO 4272009 Complex Numbers in Matlab MATLAB and Complex Numbers To start type Clsqrt l Matlab will return ans 0 10001 C2sqrt 3 Matlab will return ans 0 173211 4272009 To enter a complex number type c3 451 To find the conjugate of c3 type conj c3 You may ask for the real part of a complex number by typing real c3 Imaginary part ofthe number can be obtained by typing imag c3 To enter a complex matrix enter it in the same way that you enter a real matrix A 21 3 51 2 397i 67i 55 121 1 n 200l00i 300 500i 2000 0 700i 600700i 5500 1200i You may find the real part imaginary part or the conjugate ofa matrix by typing the following commands real A imag A conj A 4272009 Exam 1 Wednesday February 11 2009 Material for the exam gt Quiz 1 gt Lab 1 to Lab 4 gt Lecture notes up to today Feb 9 2009 httpZZpersonaIgeorgiasoutherneduquotr baSPRINGZOOQmgr1731509html gt Chapter 1 of textbOOK not including Loops ENGR 1731 bomputlng 10139 unglneers Mechanical and Electrical Engineering Technology Lecture 8 About MATLAB Instructions Prof AlbaFlores MATLAB Instructions 0 In MATLAB there are three types of instructions Statements Commands Functions Instruction Line Syntax 4 Statemenb lt Command 3lt 2gt lt Function lt gt Means item is optional Types of Matlab Instructions Statements a2 b5 Command c a b dab 0 Functions x sin x plot a b if present it indicates that the result of present instruction is not shown on the screen Edition and Navigation Keys Arrows keys lt T gt ix are used to move the cursor in the command window T Scrolls back through commands i Scrolls forward through commands lt Moves backwards in a instruction line gt Moves forward in a instruction line Backspace Deletes previous character Delete Deletes next character Enter Executes instruction MATLAB Operation Modes We can use MATLAB in three different modes Calculator Mode Command Mode Program or Script Mode Matlab Operation Modes cont Calculator Mode gtgt 2 7 ans 2 9 Command Mode gtgt a 5 b 2 C a b Script or program Mode gtgt lab3pl MATLAB Basic Operators Operation Symbol Example Addition 3 5 Subtraction 545 165 Multiplication 35 10 Division or 1957 or 7197 Exponentiation A quot Assignation a 5 Variable Specification 0 Variable names are case sensitive Cost cost COST are all different variables Variables must start with a letter and the only special character allowed is the underscore AverageCost 0 Maximum number of characters in a variable name is 31 Operations Precedence Operations are calculated starting from the left with the exponentiation operator having the highest order followed by multiplication and division with equal precedence and followed by addition and subtraction with equal precedence Parenthesis can be used to change the order of precedence Precedence Examples gt 8 35 ans 23 gt 8 3 5 ans 55 gt 4quot2 12 842 ans 0 gt 4quot2 12 842 ans 3 Scientific Notation We can use scientific notation to specify the value of a number or variable 0 In scientific notation the value of a number is expressed in two parts the mantissa and exponent Examples 1000 1 x 103 233 233 x 10 2 00001 1 x 10 4 Scientific Notation cont MATLAB uses the letter 6 or E between the mantissa and exponent to express the value of a floating point number Example 1000 1e3 233 233E 2 00001 1e 4 Matlab only displays the 4 first decimal numbers Eg if you type gtgt g 0000100004 Matlab automatically will convert to g 1 0000e 005 Comments Program documentation is very important in order for other people to understand a program It is recommended to insert comments in our programs to make them more user friendly In MATLAB any line starting with a is consider to be a comment Comments Examples Form data matrix used for rotation polepolexpoley cartcartxcarty weelweexweely length of the data nengthx Textbook exercises to prepare exam 1 T131 T132 T133 T134 T142 T16 1 T162 Example related to T13 2 Consider the third order I ol nomial X36X2 11X290 a Plot the polynomial in the interval x 20 to 20 b Find the roots of the polynomial a plot X20O120 yx36x 211X290 plotxy grid b roots po1 6 11 290 roots pol 3222009 ENGR 17 Computing for Engineers Merhanica and Electrical Engineering Technnlngv Flowchar ts and Pseudocode Pruf Albszlures Algorithms An Algurlthrn ls a vvelleuenneu procedure to solve a prhhlern An algurlthrn ls a very usetul tool that a prugrammer uses to express the method thatwill be used to solve a problem Onee thatan algurlthrn lsvvell uenneu the prugrarnrner can translate lt dlrEEtly tu a speelne eurnputer language Algurlthrns can he represented as tlhvveharts hranu pseuuhehues Flowcharts and Pseudocode Fluvvcharts anu pseuuhehues are also other usetul tools that are used to plan how a prhhlern can he shlve usan a prugrarnrnlng language Fluvvcharts anu phseuuhehues are lnuepenuent htthe prugrarnrnlng language lfyuu have a good tlhvvehart hr pseuuhehue tor a glven prhhlern ltvvlll he stralghtfurvvard th lrnplernent that tlhvvehart hrpseuuhehue lrltu a prugram ln any Eumputlng language Flowchans and Pseudocode lcontJ AFlowcharls is a graphical approach to create a coding plan Apseudocode is a verbal description ofyour coding plan You may want to use either or both for your programming projects Fur slrnple prhgrarns pseuuhehue may he the hest plannan apprhaeh Example 1 Suppuse We Wanttu create a prugrarntu eunvert mp th ls The output should he a complete tahle Wlth a tltle and column headlngs Apseuuhehue thrthrs example could he De ne the veetor ofmph values Conven mph to Ms 39 the mph and W5 Vectors into an array Display the table An euurvalenttlhvvehart plannan could he C emumnonm unrirf i gm 3222009 More on F owcharrs and Pseudocode Ftewchart are etcterat rEprESEntatmn er a cerheuter prugram Ftewcharts ahe eeseueeceees are teets mtE dEd te hete prugrammers te create better cerheuter prugrams Ftevvcharts cah atse be use effectwetyte tHustrate the structure er a eregrarhte heheregrarh Ers st rh uvvchans erhehastze the tegtcat prugressmn er eeas More on owchart and Pseudncode cunt Furcumphcated eregrarhrhhg tasks the Bumbmatm er uvvchans ahe eseueeceees are htghty recerhrheheee ew charts are very userut because they hete te create a mg etcture er yuur prugram Tu create uvvchans t S recerhrheheee thatyuu use the standard uvvchamng syrheets Standard Flowchaning Symbols An ova ti used u mmca e the chmmm we a a whoquot u we r V A paIaHalvinm t used to muncate vnvut 7 av uupM ymnesses Carcutattens are Dlaced m reetahgres A mamand memes a ueesmn Dmm Example 2 Create a ewchart that Wm shew huvvthe reueWthg ereeterh can be setvee usmg a cerheuter anguage rYuu are asstghee te Whte a prugram that M evatuate whether te SSuE a drwerhcense easee ehthe aeehcaht age A evvchart that tHustrate the precess ceute be m miy haw mum hams net 7 quotW gt v mini Dvnurs m amen a sweat ham Example 3 Create a ewchart that Wm shew huvvthe reueWthg ereeterh can be setvee usmg a cerheuter anguage rYu r assgned te Whte a prugram that Wm dEtErWWE test grades easee eh the sceres The grades sheute be based eh the quuvvmg chteha meow A evvchart that tHustrate the precess ceute be 322009 ENGR 1731 Computing for Engineers Merhanica and Element Engineering Ieclmnlngv M Decision Making amp Loops 7 1f7etse117else structure Loop 7 for structure 7 While structure Prat Aibarriures If Structure Decision Implementation 1 I I ttmnm tr on in order to Implement the deClSlOn statement mums 39n LAB we have three different structures end a festructure b frthen 7 else structure c The Switch or Case structure hum npuci Encer e signed nurrher 1 1i Lnum lt m mspteyt Negaclve Numbem ls dlsplavi P slclve Nurther i end IfElse Structure If elseif else Structure 77 W mndi nn mmmunds 1 mmmunds Z Wu Hm mumswk r t t age npuci Ynur age 5 7 1 dnsplayl WELCOHE 1 322009 s Th L gram reads a nurrhel Prwlded by the s use and uutp s a 1 i t e umber S anesten then sets s a 4 sh nunnet s ies than s ZERO i t number s u E n E s umh d t um 1npuEL PJEaSE EnEEI s numhe 1i num gt u textwnusntwe nunher elseli num lt u text l negaclve number text L zERo 1 nd iprlncil rne nurrher 13 s a s n nun text Loops Imps pertdrrn dperatrdns repetrtwew There are tws types DHDDpS A for map ends aner a spesmed number a repetrtrdns Anniie map ends an tne nasrs dva ugma undmun Tne t or structure A for structure repeats statements a spesms nurnner unrrnes Its genera syntax rs for index staxt step finish statements Thelur uup dperates asldudws The index rs avananxetnatrs set at an mma Va ue staxt Tn e prugram tnen ssrnparestne index wrtn a desrred na Va ue finish utne index s esslhanurequa lulhe finish tne nrdgrarnexesutestne statements wnentne prugram reasnestne end hnelhal marks tne end dune uup andtneindex varranxe rs rnsreased by e st 2p andtne prugram maps back up tdtne tax statement The prudess ssntrnuesuntutne index nesdrnes greatertnattne finlsh Va ue Attnrs pdrnttne uuplermmales astne prugram duwnl n skrns DlhEh errnrnedratexyvdudwrng tne end staternent Flowchart of for statement nueie r m n ner tr lam mn HUN 322009 Examplel for 1 15 d15p1 Nute that lfthe step value ls nut shuwnthen the default value ls 1 Example 2 for 1ne11 DUSPQI Example 3 Add the following vector using a foreloop Gmdes10 20 30 40 Gmdesyi ya 93 94 lril39tl39al sum ls zero for i 114 91 llwdexlnltlallzatlon Sum Sum Gmdeslil Repeti ti ve statement en Newvilue DldVilue While Loop Tne whllealoop is used for processes in wnicn we don t know tne number oftlmes 39t nas to be repeated putwe nave a condition tnat ends tne repet on WhlleaLoop syntax wliile condition monds end WhileLoop Example Add tlie followl39rig vector using a whllealimp Grades10203040 Gl adesgxg2g3gll Su Summatlon lnltlallzatlon l139 lr idex lril39tl39all39zatl39or i whlle l e ending condition testing Sum Sum Gradesll39l repetitive statement 1 l39ritlex uptlating wnile loopsare a nice way or avoiding counters irvou duri t need to use tnem andror executing a loop only it necessary Oncetne loop isentered repetitive execution ortne statementsinsidetne loop continues untiltne logical test at tne peginning ortne loop isno longertrue Example a1n whlle agt2 aa2 Another example Usi ng tne iE else structure wri39te a program that can be used to calculate the followl39rig functh y m5 farxao I x farxlt0 Where a i39s a constant y 4132009 ENGR 1731 Computing for Engineers Georgia Southern University Mechanical and Electrical Engineering Technology Spring 2009 Functions Prof Alba Flores MATLAB Functions A function is a program that can be called inside another program MATLAB has many built in functions that can be called to calculate arithmetic logarithmic trigonometric and special functions A list of functions available in MATLAB is given next 4132009 Common Matlab Built in Functions sqrtx Square root function expx Exponential function Iogx Natural Logarithm Iog10x Common logarithm cosx Cosine function sinx Sine function tanx Tangent function acosx Inverse cosine function asinx Inverse sine function atanx Inverse tangent function Function Calling 39 In order to execute a function we just put the name of the function and assign its result to a variable v tanx Function calls 2 cosx sinx39 Input and Output Variables of functions 39 When we call a function we need to specify an input variable to be used for the calculation of the function and the function will return a value that will be assigned to the variable that we define in the calling of the function 39 Z c sx smy Output variable 2 Input variables x V Input or arguments variables Output variable Functions Advantages An important advantage of having predefined functions available in MATLAB is that we don t need to write a program ourselves in order to calculate the required value of the function we only need to call the function whenever we need it in our program 4132009 User Defined Functions Any program written in MATLAB can be converted to a function so that we can call that program inside in another program This is very convenient because it makes the programs more efficient and smaller The conditions needed to convert a program into a function are given next User Defined Functions cont We need to specify a unique name to the function We need to specify the list of input variables or arguments needed by the function We need to specify the list of output variables that are returned by the function 4132009 4132009 User Defined Functions cont 39 Function Definition Syntax function Output Variable List function name Input Variable list end Description function outl out2 funname in1 in2 defines function funname that accepts inputs inl in2 etc and returns outputs outl out2 etc All functions should end with the instruction end You add new functions to the MATLAB vocabulary by expressing them in terms of existing functions The existing commands and functions that compose the new function reside in a text file M file funnamem Function Definition Example 1 function factorial facn factorial 1 for i 1 n factorial factorial i end end Function name fac Output variable factorial Input variable n Function Documentation This function can be used to calculate the factorial ofan integer the input variable is the number to calculate the factorial the output variable is the factorial of the received number function factorial facn factorial 1 for i 1 n factorial factorial i end end Function Definition Example 2 function sum sumanum1 num2 num3 sum numl num2 num 3 end Function name suma Output variable sum Input variables numl num2 num3 4132009 wrenlDIrulnrY u a x v Ma functlun sum sumam numz num 3 mOr 1 numZ mm gtgt natal suma561m coca or Dncumenlsandszl n raiba vbmxmznfsm F e m rm Ga 2 max Debug mama Wndaw Haw ta M F a f Function De nition Example 3 We can create a Mattab We caHed stat m that de nes a new fu nct39wun caHed stat that catcu ates the mean and standard deviation ufa vec or function mean stdev statx n lengthx e n s mxn stdev sqrtsum x meanA2n end Function name stat Output variables mean stdev Input variable x 4132009