Você está na página 1de 32
Appendix A Introductory MATLAB Core Topics User defined facts and uncon es (A) Staring with MATLAB (A.2), Anenymeus uncon (8), rays (3), Functentuctons (9) atematial operons with arrays (A. Subfunctons (A10) Sent is (A) Progaming MATLAB (A.1), Poting (6) ‘A’ BACKGROUND [MATLAB is powerful language for technical computing, The nae (MATLAB stands for MArix LABoratory because is basic data el ‘ment isa matrix (anay). MATLAB ean be use fr mathematical con Puttons, modeling and simulation, data analysis and. processing, Visualization and praphis, and algerithm development ‘MATLAB is widely sod in niverstis and elles in introduc tory and advanced courses in mathemats, sien, ad epevialy ‘engineering. In industry the sofware suse in reser, develope, and design The standard MATLAB program has tools funtion) tht fan be used to solve common problems In adton, MATLAB hes ‘optional toolboxes that are a collection of specialized programs designed to solve specific types of problems, Examples include oh boxes frsignal processing, symbolic calculations, and conta sytem “his appendix is a bit inedstion to MATLAB. I presents thy ‘most basi features and syaax dat will enable he reader follow the use of MATLAB in this book. For 2 mare complete introduction, the reader is refed to M ion wi Four Eeition, by Amos Gilat, Wiley, 2011 A2 STARTING WITH MATLAB, Wis assumed tht the software is istaled onthe computer and that he user can start the program. When the progr is running, eight win dows canbe use ist of the various windows an the purpose tiven in Table A-L. Four ofthe windows—the Command Window, the as 7 compile exeson tat canbe ade up of miners anor va tbls Faction em a enue in puna ar wel ain expe Som The flowing hows ctanpesof tng te het STU ca) en MATE ted cur wih Sala > saree) ee a) b> oqeetst + Seaqze(ton)) TT) >> as + 60074) /agee cian TTS) Liss of sme commonly used eemeniny MATLAB mates tein fncoe ae Benn Tal A. A comps st of fnctons rg cats ent fond nh lp Window. . 2 Bata eentay mathe [Command Pectin Foam Sart eh Beare Ps mec oo Esper a) jabs (x) [Absolute value. 7 [>> aba (-24) Logix) Natural logarithm, [>> 209¢1000) | Barges ene Testo Beep b> esto aT sine Socofanglex Waa) bo ain 7a) a inate | sin ong in dere. 2.30 2.3000 Ta ober igus Fincons ae writen ine ane wa. Thelnvene gonna Rens cen yang the eri a for exampl ao EF ‘Ad. Sartig wit HATLAB ug, 42: alsin elementary math functions (Continued) [Comnana Denon samp Foundiay Rowdies nearer D> soma fix (x) /Round toward zero, a7 >> fix) [ssid Rnd ap oad aay ro) floor (x) ‘Round down toward minus infinity. 5 acorn a | Dip formas ‘The format in which MATLAB displays ouput on the sexeen can be ‘hanged by the wser. The deftult ouput format sxe pont with ar ‘ecimal digs (called short). The format ean be changed with be format command. Once the format command is entered alle ‘utp that follows wil be dsplayed inthe speifed forma. Sovra of ‘he availble formats are sted and deserted in Table A. le AS: Dipl format Command Descriptn Trample format short | Fed point with four decimal dighs x [> 29077 001 Sumber «1009 soe = Orberwis display format shoet ¢. _ | 41-4286 format Yong [Fined poin with 14 decimal digs fon > 29077 0001 Smumber 100 lane Otherwise display format Long & ‘azesneesres [format shorte [Scene notation with four decimal [> 29077 sists [format Tonge | Scene notation wth 15 decimal Gig: [> 0/7 [Format shortg | Bestof digi ixedorfoaing pont [>> 39077 Format Tong g _ |Bestof dig fixed or Noaing point [>> 29077 20 Appendix A Inoduetory MATLAB “Tible A: Display format (Continued) Command Deseipton oer Tommae bank [Twodecimal igs >> a7 | ‘A ARRAYS. ‘The amy is a findametal form that MATLAB uses to stre and ‘manipulate at. Aa aay i list of numbers anged in ows andor colunns. The simplest array (one-dimensional) sow, oF a column of ‘numbers, which n scence and engineering i commonly called a ee- tor, A more complex aay (tvo-dmensional i collection of numbers arranged in rows and columns, which in ssince and engineering is called matix. Each aumber in 4 vector of a mai is called an ele ‘ment, This section shows how to const vectors and mies. Seo tion A. shows how to amy out mathematical operations with rays (Creating esector In MATLAB, a vector is rated by assigning the elements ofthe vector to, variable. This canbe done in several ways depending onthe soutee ofthe infoemation that suse forthe elements of the vest. When ¢ ‘ectr consis specific numbers tht ae known, the vale of each le ‘ment is entered dietly by typing the values of the elements inside square racks: Tronber sunber number] ora row vector, he numbers are (ped Willa space or @ comma between the elements Fora column vestor the nurs are typed with 8 semicolon betveen then. Each element canals be malematical ‘xpresion tht can iolude predefined arbi, number, a Tne tions. Ota, the elements of' row vector area series of mums With ‘constant spacing In such cses the vector canbe eeated by ping where is the fit clement, isthe pacing, and the Is cement. Another option sows the 1 :nspace command: Several examples of constructing vectors are >> yee (2686 1906 2988 1990 1992 4996 1996) see 1986 2988 1990 19929081996 >> pat = (2 & 8) (Ci ery ie) AS amays — = 21 ‘ 5 boxe (zat Ee] 2305 7 9 2 as ‘© 1.6000 3.2000 4.8000 6.4000 8, 0000 Creating a o-dimensional array (matris) A two-dimensional ara, alg called a mati, has number in rows end ‘columns. & matrix seeted by assigning the eetentsof te mats 8 aribl. This is done by typing the elements, rw by row. inside square brackets [], Within each row the elements are separated with spaces or commas. Between rows tye or he press Ener, ‘variable _pane= (Ist row elements; Qnd row ele= ments;....} last row elenents] The cements that are entered canbe numbers or mathematcl exprs- sions that may inlude numbers, predefined variables, and finctoss llth ws must have the same number of elements, IF an element is 20, ith io be entered sich, MATLAB display an err message if fan tempt is made to define an incomplete max. Examples of matic ‘es rete in difirent ways are peasi8 35.63; 476 1) 2132 40) SSR) 5 3s cnt pped= 6: en 3; baa: TUR) D>Mat =e, oh, contpi/3}s We, egeeChMb/ed), 241 Fema) 3.0000 24.0000 0.5000, Saal eee 26.0000 “tles30 a4.0000, se +All variables ia MATLAB are arrays. A salar a rey with one clement veto isan aray wid ose row, or one clu, of ‘ment; anda matrix isan aay with elements in roms and eons, + The variable (cla, vector, or matrix is defined by the input hen the variable sasigned. There is no need to define the sve of be amy (single element fra Salar, srow or column of elements am —_—— Append A Introductory MATA «vector, ora two-dimensional aay of ements for matin) before the elements are assigned + Once a variable exists a8 seal a veto, ora mati, it cam be changed t be any other size, or type, of variable. For example, a Sscalar-can be changed to ¢ vector ora matt, a vector can be hinged to a salar a vector of diffrent length or a mati, and & ‘mati ean be changed to hive a difleent ize, orto be rece 03 ‘ewtr ora scalar These changes ae made by ang or dletngele- Avay oddresing "Elements in an aay (ihe vector or matin can be adresse individ sally oi subgroups. This sel when there sa ned to redefine only Some ofthe laments, or 1 use specific element io calculations, for when a subgroup ofthe lements is sed to define anew vaable “The address fan clement na vector its poston in the ow (or column). For vector named ve, ve (refers to the element in pos 'on Theft postion i 1. Fr example, fhe Wetr ve hat nine ele wen 35 46-78 23.5 14 813.55 then ve) =23, vl 7) = 81, and ve(1) = 38 ‘The adress of on clement ina mutrix is its postion, defined by the row number and the column number where i ie located, For 8 matic asigned ta variable ma, matkz) refers to the element in row k fd column p. anes e710 Forcxample ifthe matix is: ma = ‘en, ma(1) = 3, and ma2,3)= 10 Ts possible o ehange the value of one element by reassigning 3 ‘now valu to the specifi element Single elements ca also be used ike ‘arial ia mathematical expressions. ao vere(is 46 78 235 14 a1 3 58) GEE) ver(e)ean8 >> vor(s)“VeT{8) + eqee (VERT) ==) po ware (3 11.65; 4710 2) 13.9081 Dear 3 ou 6 5s >> sa9(9,2) =20 au a "7 a 3 2 5 0 6 >> yar (2,4) -mar (a2) EE Using a colon in addressing arrays ‘A colon can be used to addres range of elements ina vector ora ‘mati. IF vector, vale) ef to elements m trough nof be isa matric Cees tothe elements inal the rows of column Ales othe elements inal dhe columns of row mA) retes ‘othe elements inal the rows besween columns and mn.) refs 1 the elements in all he columns beeween rows m and n Almengss) refers tothe element in rows though n and columns p though 9 dows [¢ 45 8 12 34 2 50 23 23) EEE] fas a a 2 se a on peusvia:7) (eae ie em a bo 2 50 peas t1 357.9 11) 2468 1032) 36912 15 18; 4832 16 20 24; 5 40 25 2025 20) Die MATLAB has many tuiltin fansons for mansging and handling aay. Several ee listed in Table A “Tbe Acts Bullen funtion for baning arrays [Commana Deserption ample fiengeh Retuns he amber of clemenisin ves [>> A> (8 9 2 a] oe 35 Leagen fsizetay Retans wrow vevor (mya), where [>>Ae (61 6012) 519 6 8 A) and nar the ice mr of he ary 8 (eis sumber of ros numberof columas.) eros inn) reas a ai wih mr rows and nook umn in Which al he element ae the umber. fonestm ni reais a at wih rows and nook nnn which al he element ae the umber ever reas a squve matin wih maw and columns in which the diagonal ele ent are equal to 1 (identity mattis). Sirings +A string is an amay of characters. tis rete by typing the charac ‘ers within single quotes. + Strings can include eter, digs, oter symbols and spaces + Examples ofsrings: 'ad of, 1382", *fedeba:21!" ‘+ When a string is being typed in, the color ofthe text onthe sreen changes to maroon when the int single oot ie typed, When the Single qoote atthe end of the string i pad the color of the sng changes purple Sings have several diferent uses in MATLAB, They ae used in ‘output commands to spay text messages, a fomting commands of ns los, and as iaput arguments of some fetions. Seings can aio be &ssignd to variables by simply ping the sting onthe righ side ofthe ‘ssgnment operator, as shows inte next example Frey 6 >> Ba 'My mane Ss John smith’ My name 48 John saith ‘Ad MATHEMATICAL OPERATIONS WITH ARRAYS (Once varibles are created in MATLAB, they ean te sod in a wide ‘arity of mathomaticlepeatons, Mathematical operations in MAT: LAB canbe divided into thee eategoies: 1 Operations with seals (11) arays) and with single elemenisof| arays 2. Operations wih rays following the rls of inca algebra 3. Hlemeneby-element operations with aay Operations with sal and single elements of stays ae done by ‘sig the standard symbols asin eaealator So fa alte mathemati cal operations inthe appendix have heen done in this way. Addition and subtraction of arrays Wit ray, the atin, subustion, and multiplission operations fl: low theres of near algebra (se Chapter 2). Th operations * (a ‘ton and ~Gabrction) ean only be cz out with says femal size (he same numberof ows and columns) The sum, ore dif ence of to aay, is obuined by ang o subtracting, thei coe. sponding elements. For example, i 4 and are two (2 3) matrices, «slit ot offend ‘hen, he matic that is obtained by adding 4 ands au +8) 42) y+ 2,3) 45 #3) (a +B) (a) +P Im MATLAB, when a scalar number sade to, or subtracted fon, nara, the number i ade, or subtracted foal he elements of ‘he ana Examples ae >ovae (a 5 4); vee i102 71 Deas {Ss -34; 92 0), Be [20 74; so 9 230 Mulepication of arrays ‘The multiplication operation * is executed by MATLAB according to ‘he les of linear algebra (ee Section 241), This means tat if al 8 ae to macs, the operation 4 canbe cared out only if the Ram. ber of columns in matric is equal fo the numberof rows in mst 3 The result i matrix that has the same numberof rows as 4 and the same numberof columns as 8. For example, i693 2) eat and Gis a (24) matrix, then the operation C=A"2 gives a (94) mab Dae(2 1; 83; 671, Bel 9 1-3; 5.246) (KiReMETETD) boa 5246 peenen (REE) ce 33 16 -2-12 noe ee ‘Two vectors canbe multiplied only if oth have the se number of elements, and one is 2 10W vector andthe other i lum vector The tuition of 3 row vector times a ofumn vector gives a (11) ‘atx, which is @ seal. This isthe dot product of two vector, 'MATLAB also has a bulin function, named do (a,b), ht om ites the dot product of two vectors} When using the dot fonction the ith Arrays _ an vectors a and b can ech be a row or column vest The multipin ‘on of column vector times ow vector, bath with element ives an (ox) mls, su pesre bi ta at Array disision ‘The division operation in MATLAB is associated with the solution of system of liner equations, MATLAB has two types of aay dvisin, ‘hich are the Ie vision andthe righ division. Te vo operations at explained in Section 481. Note that division for defined operating fn inst algebra (ae Seton 2.1). The division operation in MAT TTAB performs the equivalent of muliplying a mati by te inverse 3f pote matic (or vice ves). Element-yelement operations lemet-b: [xponentaon X__ [tet Division If two vectors @ and b are a= [iy a 0; a) and (95. hn cence utp, isn sede ote re 2 1b [a/b a/b 0/05 0/0] abe fen eo | ve mtd an ae fae ia [au Ba, Ae lta dads] aod B= |e, Be 8, Las ds An ls # Ba) then element-by-clement mutplicaion and division ofthe two mats- cose fst ABs ABs} [eu /By A/By Aw’ tpn | 48a Afar AB a= | Asy/By, Aay/Bos dy/Biy [ss Auber Als] Ay (By An/B Ay! Examples of element-ty-lement operations with MATLAB ae paces ses Bgl peep to; 327 Pa) 3% "2.0000 1.8000 0.3000 ilessy 410000 olsnte 4 Mathematel Operations with Arrays 429 lemen¢-y-clment caleulatons ae very useful for aleulating he ‘ale of function at many values of is argument, Thee done by Tis “ining a vector that contains values ofthe independent variable and then by using this vector in element by-alement computation to eat {vector in which each elements the comesponding vale ofthe fue tion. For example, calculating. y for eight values of s, 1,3,5, +15, is accomplished as follows; pees [22:28] Camere RTE) 1 305 7 9 1 a3 as dove (2.734 Seay ./(4¥2.°2-10)) 2 Sabon of eens of er ooo 1.6154 1.6667 2.0323 2.4650 2.9241 3.3964 3.0764 Inthe lst example clement-by-A= (89 AT ean Value oft element ofthe veo- >> mean) [eunG)____]IF Risa veto the inetion ets the [>>A 189 al sumoftheclemensafthe vector >>) jrorems fava ven the inctonanangesti [>= 89 2 | elements ofthe vector in acending [>> #9580 jose ya ss laa "The fnction ears the diomnimantoF |SSA= (243 ST? Sanco a square mati 430 Appendix A Inrodvcory MATLAB AS SCRIPT FILES. A serp fle i fle that contins a soquence of MATLAR commands, ‘which als called program. When seri ile sun, MATLAB exe cates the commands inthe ocd they are ‘writen just aif hey were 'yped in the Command Window. When a command pencats ouput (ee, asignment of vale toa varitble without semicolon thee), the ouput is displayed in the Command Window. Using a srg ile is ‘convereat because it can be stoed, edited later (coreted andor ‘chnged), and executed many times. Sci ils canbe typed and edited in any text ete and then paste into the MATLAB editor. Seip files ae also called fies because the extension mis wsdl when they are saved Creating and saving a scrip fle Scrip files are crested and cited inthe Editon Debugger Window, Tis ‘window is opened om the Command Window. In the Fle men Seloct New andthe slot Mee. Once the window open, the con ‘ands ofthe script ile ae fyped ie by line. MATLAB automaticaly snombers anew line every tne te Enter key is presse, The commands aa be sped in any tex editor or word prooseor program sti then ‘copied and pastd inthe Eien Debugger Window. ‘Before a scrip ile can be exzcutd thas o be saved. This ie done by choosing Saves. fom the Fue mens, selecting location (older). and entering a name forthe file. The rls for naming «srg fl fee low the rules of naming avaiable (mst gin with eter, can inshe digits and underscore, and be up o 63 chiracters ong). The names of| user-defined variables, predefined variable, MATLAB commands, of fuetons shuld not be used to name Srp es. ‘A srt ile can bo exacted ether by ping is name inthe Cont rand Windows nnd hen psing the Ftor ke. or dey from the Editor Window by clicking on the Rum ico. Before this ean be done, however, heuer has to make sure tat MATLAB can find the file. that MATLAB knows where the il is sve), In onder to be able ort the fle must be in either the cutet directory or the search path “The caren diretonyis shown inthe "Curent Dizetory” Ald in ‘the desktop toolbar of the Command Window. The cutet directory ‘an be changed inthe Curent Directory Window When MATLAB is aod to run script le orto execute a fane- tion, it searhes for he file in directories sted inthe search path. The oplot (x igre At: A plot of dat points umber (value of variable the pe command bas the form: ‘ering #-5.2% additional text’ variable FFormating elements Theme ofthe (Gafie the format of variable whose ‘he nuke). ‘ales spayed AG PLOTTING [MATLAB has many commands that can be used fr erating diferent ‘ypes of plots. These incode standard pots with linear axes, plots with Togarthmic axes, bar and srs pots, polar plots, nd many more. The lots can be formated to ave a desired appearance, “Twordimensional pls canbe crested with he pot command ‘The snes form ofthe command is ‘The anumenis x andy are cach a veto (one-imensional aay). Bath ‘vectors must have the same numberof elements, When the po con rand is executed, a gure is appears in the Figure Window, which ‘opens automatically The igre tas 2 single curve with the ales om the abscissa horizontal ans) and the values on te oxdnate (vertical ss). The curve i constructed of straight ine segments tat connect the Points whose coordinates ate defined by the elements ofthe vectors x andy. The vectors, of couse, can have any name. The vector tha is ‘yped ist in he p10: command is used for the horizontal ai, and the ‘eee tats rypod second i se forthe vercl ate. The Sgue that Je diaptnyed nor as with near sale ad deal sane, Fon snmp ita vector x has the elements 1,2, 3,8, 7,758, 10, anda verry has te elements 2, 65,7, 7,53 4,6 8, simple pot of) versus canbe produced by fying te fllowing in he Command Window 238778 8 ay 65.7755 46 al; D (Once the pict command is execute, the plot that is show in Fig. AS Js displayed inthe Figure Window. “The plot command has additonal optional agument that an be use fo specify the eoler apd style of the ino and the coor and type of marker, if any ace desired. With these options the command asthe 3 Plot ey, ine apeciti Line specifiers can be used to define te jl and color ofthe in nd the type of markers (if markers ae deste). The ine style spectaes Lineseye [Specter [ine site | Speciter el etaiy bed ‘The ie cole specifi ae: Line Color | Specter | Linesihe | Speiter [ine Cate | Specifier | Line Color | Speier ae 7am yellow = [ie 2 Figure 4-2 Formate po. ‘The marker type specifier are: [tanker | Specter [ Marker | specter | Marker | Spectr passin [+ | ise 7 [sre = [sce [psi aan a “The specifiers ae typed inside the Lot command as strings. Win the sting the speifies canbe yped i any oder. “The pLot command creates bare plots. The plot canbe modied to include axis label tte and ode features, Plots canbe lorie by using MATLAB commands tat fllow the plot command. Tho fonmating commands for adding axis labs and a ite are wlabel (‘text as string’) Vlabel (text ae string") tte(‘eexe as string’) For example, the program led below prodoces the plot that i i= played in Fig. A-2. The dat plowed witha dashed redline and aser- ‘sk markers andthe figure inclddes axis labels and a ie po yes (1988;1:2994) dpele=(® 22.20 22 18 24 27) Do plotiye,ele,‘=-r*", ‘Linewidth’ 2, ‘mackerai >> xlabel (YEAR!) >> ylabel (‘SALES (uL2isons) ') >> title (‘Satee Records) 2) Formatting of plas can also be done ia the Figure Window using the insert men or Plt Editor. AT USER-DEFINED FUNCTIONS AND FUNCTION FILES: ‘A function in mathematics ean be expressed in the form y= #0, ‘where fs) is mahematicl expression in terms oF =. A vale of (ouput is abainod when a value of = (input) is substiuted in the fexpression A function file in MATLAB isa computer program tht i ‘sed like a math function, Data imported into the program snd is sed forcalcoating the value of the function, Schematcall a unctin ile ‘an be lusts by Input dita [Function] output data File ‘The input and output arguments can be one of Several variables, and cach canbe a scala vector, ofan aay of any size. Function can be tse fora math faction and as suprograms in large programs. In this ‘roy large computer programs can he made up af smaller “bulding ‘locks that ean be tee independently. ‘MATLAB has already many builvin functions. Examples ae the standard ath futons (je. sin(x), cos (x), sare (x) and ‘up (that are used by sping their name with 2 alue forthe input Segue, MATLAB contains also many builin functions fr exccut ing more complicated operations (eg, solving a nonlinear equation, cae fiting). "MATLAB users can write addtional (new) user defined functions that canbe used like the bule-in functions. This section desis ow to write, save, and use user-defined factions. ‘User-defined functions are crested and edited ike script ks, in the Editor Debugger Window. The ist executable line ina funtion le ‘ust be the function definition ine that has the form The wor finn Trewerdfinion | / xiwotouptmpunens The nine of Alston waumens imattetefintwe / Sr insactc sal Ch fncn, Spel iie prio dunt opedin ted conms Sateen The word “nin el nave ct eer mt eh ft ‘worn the funesion defini lise. The input and ouput arguments are 5 and Function Fis 85 sed to transfer data into and ou ofthe function, The input arguments relied inside parentheses fllowing te funtion name Usa thre ‘satleast one input argument there arena than one te int ae ment are separated by commas. The computer cae tat peters ¢alelations within the fantion files writen nem of the inet a mens and assumes thatthe arguments have assigned numeri value The ouput arguments, which ae sted inside brckets on te et side ofthe assignment operator inthe function definition line, ansr the output fm the faction ile, user-defined funtion ean ave oe, several or no ouput arguments. If there ae more than on, the out agumeats are separated with commas or spaces. If there only Se ‘utp argument, itean be typed without racket In onder forthe use > {eanth total] =108n(25000,7.5,¢) 00.72 cotal= 20634.07 AB ANONYMOUS FUNCTIONS ‘An anonymous fanetion isa simple (onein) user-defined function ‘hats defined withou creating a separate funtion file (Mf), Anon ‘mous functions can be defined in the Command Window, within a Script le, or inside user-defined function ‘An anoaymousfantion is ected by typing the following com sand: ‘Thename of tnony- TSG Ait ofinput ang Mathematical moss fection symbol. mene independent expression, vale), Asimple examples cube = @ (x) x93, which calculates the cubic power ofthe input argument. +The command crenes the anonymous function, and assigns a handle forthe function wo the variable name that son the le-hand side of ‘the ~ sgn. Function handles provide means fr referencing the fine tion and passing itt other functions, See Section A + The expr consists ofa single valid mathematical MATLAB expres- 5 Anonymous Fustons + The mathematical expression can have one or sever independent Yarables. The independent variables) 1s (ate) listed ia te (arg2ist).Ifthere are mere than one, the independsot vail se separated with commas. ‘An example of ap anoaymous function that has two independet vatabes si cizcie = @ (x,y) 16°2°249"y°2 + The mathematical expression can iaclade any built-in or wse- defined factions, + The operations in the mathematical expression must be writen ‘sccoding tothe dimensions ofthe arguments (eleent-ty-lemert ov linear algebra cleans), * The expression can include predefined variables that ae already 4efined when the anonymous function is defined, For example, thre variables a,b, and «are defined (they have asignd numerr «al values), ten they ean Be used inthe expression a the ano. ‘mous function: parabola = € (2) avx"2sbex-e. Importa ‘ote: MATLAB captures the values of the predefined varble, when the anonyeous funtion is defined. This means that fue quently new values are asined to the predefined varbles, the snoaymous fiction is not cinged. The anonymous fancon fast be redefined in order for the new values ofthe predefined varibles to be sed in the expression of he anonymous funtion sing an anonymous function * Once an anonymous funtion is define, it canbe sed by typing ie fame and a value for the argument (or arguments) in patctheses (see examples tht follow). * Anonymous functions can lo be used ts arguments i othe fnc- tion (se Seton A), ‘Example ofan anonymous function with one independent variable: Ba dow) as an anonymous fantom for a5 eae by: ‘The function: x) = 2 can bo defined (in the Cocmmand Win D> ER = 0 Uw) oxp(e'2) /eqet(x*2e8) 4a semisolon snot ype at the end, MATLAR displays the function ‘The funtion can then Be used fo diferent values of e198 438 4 ntrdactory MATLAB >> = me) {fis expected tobe an ary, and the function calculated foreach ee- ‘ment, then the fenetion mst be modified for element-y-element loi Tatoos. D> FR 6 (x) expe. "2) /aqeetn.“245) wpe (x72) eget 245) >> maT. 0.5 2) ee) Taos 0.5604 18.1996 Example of: ables ‘The finetion f,9) futon by >> mA = 8 Gey) 22 ‘acm wiaearanaenryty2 ‘Ten, the anonymous function canbe use for diferent values of and 3 Foexample, ping 8A (2, 3) gives: wth several independent vari ay +? canbe defined as an anonymous > m2,3) AQ FUNCTION FUNCTIONS ‘Thee ae many’ situations where a finetion bas tbe jmmpored into nother funcon. For example, MATLAB has builtin foeton called #2620 that finds the zero ofa math function (x), i the vale of where fx) = 0. The program (code) ofthe function £2> paenontunplot @Ren0,0.5,40 WS go00 2.9002 | nia nwarins | 2.2500 “3.5548 : 0000 “0.6235 |When the command is executed the numerics outputs displayed inthe Figure A unplot 4a —; Command Window, ad the plot shown nh i. Ai splayed a 7), to Figs Widow _/ Pasian namo ton in tno nto To wea anonymous —fincton, the fet fis) = etd 26 6 fst as oe writen a8 a Bony | tno, andthe pasted ino heuer neon Fung loe. The TTa-y-—+ lowing shows How bah of tes tps redone i the Command ‘indo: Note ta the mame ofthe anonymous function Feensnnory i ented without te sgn @ forte inpuragumen Fun in Be we Glined fincton FunpLot (ce he ame isaeey th handle of te snorymous inte). Plterested by >> Raamonnony= (x) exp (-0.274x) 13-93-20. 9240.80-3 Pee NOY eo aoe) te.nb2ta."200,00e-3 Tole Co.20 recsancae.tns LEER) >> yaenontunptot (Pdamoanony0.5,4) wens ooo 2.0082 Gasman 10 SUBFUNCTIONS, ‘A function file can contain more than one use-defined function. Tae fictions are typed one after the ott. Each function begins with a fiction definition ie. The fst function is calle the primary function sn the vest ofthe fintions ae called subfanctions. The suboncons ‘an be typed in any onde. The name ofthe function file thats sad Should corespond tothe name of the primary funeon. Each of ie functions in he ile can call any of he cer fueton in the file Ot- fide funtion, or programs (sci ils), ca only ell the primary fre tion, Each ofthe fnctons inthe leas is own workspace, whish ‘cans that in each the variables ae loa In eter words, te primary fiction and the sbfunctions cannot access each ofhers variables (nes variables are declared‘ be soba). ‘Subfunctions can help writing wser-defined Tantus ia an oes ized manne. The program ia the primary funtion canbe divided ito smaller ass, where each scarred out in asubfunction. This deme ‘ted inthe lowing werdeise fnon nue S02 Unve9D- The input to the funtion is vector sith numbers (grades). The Tune sot the vector fom the smallest element to te lrgest and cacultes the average andthe standard deviation ofthe grades. The function ca tains tyes subfustons, The average, (nen) of ven set 0» umbers nis ven by a erereny a 4a. Appendix A ‘The standard deviation ie gven by: er) function (GrSort Grive ors] = sortavadsiGeades) sorthves sorte a vector that contains grades from the amall~ {Jervese, calculates the average grade ans the standard devis- § ourput arguments: \ Gesore A vector with the grades ie length Grades) Season ate Seen ame; ee Seca, —— cream (Nem) Sati i function xrorted = Lowfolligh (x nua) [ KARGSia ta aaa fort = anand Geavecr on emule | for 3 = ietsnom tage J feag) xe Senex) xaesG)) x)= temp? on function aiiv = standoiv(x,nun,ave) [ AahioxoniaTataine ie saiez = (cave) "2; ‘ide evi oe cen Saiv = eget (eomentisa)/toumeay); [Sve Next The userdeind fonction SortAvesD is used (aed) inthe (Command Window sic cgeaal ‘AI Progeammingln MATLAB - 48 >> Classceades = (80 75 91 60 79 69 65 60 95 50 S11 >> [@.A 8] = sortaveso (clasacrades) 0 Ce =) 11 PROGRAMMING IN MATLAB A computer program is sequence of computer commands In sme rogram the commas are execued ope ater the other into ordr at they are (ped, Many stuatons, however, require more sophisticated ‘motrams i which diferent commands (or groups of commands) se xccud hen the program is executed With diferent input variables. Inter stations there might bea nod o repeat a sequence of com ‘mands sever tines within a program. For example, programs tt solve equations numerically repeat a sequence of clelations until te ‘vor inte anrwer fsa than some measure [MATLAB provides several tools that can be used to cont! flow of program. Conditional statements make it possible t skp oom nnands oft execute specie groups of commands in diferent sis tions. For loope and wenie loops make it posible 10 repeat a sequence of commands several ings. ‘Changing the flow of program requites some kind of deisca- raking process within the program. Te compuisr must decide whats torexeeue the next command orto skip one of more commands sod ‘continue at» different kine i the program. The program makes tse evsions by comparing values of arabes, This x done by sing el ‘ona ad logical operators ALIA Relational and Logical Operators Relational and logical operators are used in combination with oer ‘oman in order to make decisions that contol th Mow of 2 com ter program, A reasonalepertor compares two numbers by de ‘ining whether comparison statement (eg, $<) ste or false If the statment is tu, ts assigned a value of 1 Ifthe statement if fake, iis assigned a value of U. Relational periors in MATLAB are pte inthe able that follows RelaionalOperatr | Description | Relaonal Operator Deseripos = Teeth = Grater reo > Greer = Era 46 ay Tectvin [Raster [won| arts egal = Rotem] [ot tht the “equal to” elton operate consis of wo = sgn ith ro spate between them) since one~ sign isthe assigment operator In all elational operators that const of two characters there i no space betwoen the characters (==, >=, =), TWo examples are A logical operator examines te/alse statements and produces & ‘esl that ste () or false (0) according to the specie eperta. Loge ical operates in MATLAB are Leglea operat ——* | vample: AGB. T | ow Example: AB [Operates on two operands (A and B), either one, or bot are wus, the ‘Operates on two operands (A and B,Irboh are (Dy onherise the results fae (0), real ee (1); thers (bath a false) theres false (0. = NOT vamplet~A ‘Operates on one operand (A). Gives he opposite of te operand. Tre (I) ite operand is false, and fase (0) ithe pera sre boar Logical operators can have number as operands A nonzero numbers ‘ie and sero i falc, Several nap ae a ET) A112 Conditional Statements, i-olse Structures A conditional statement is command tha allows MATLAB ta make 3 ‘cision of whether to execte a group oF commands tht follow the ‘eoditonal stemen, o¢ to skip these command, In a conditional ‘11 rorammingin MATLAB statement, a conditional expression stated. If the expression is tr 3 soup of commands tat follow the statement is exeeted. Ifthe expres ‘Sin fe, he computer skip the eroup, The end structure ‘he simplest form ofa conditional statement isthe f-en strate, which is shown schematically in Fig. A~t. The figure shows how fhe commands ae typed inthe program and presnis Nowe tha yt boliclly shows te low, othe sequence, in which the commands sre executed. As the program execute, it reaches the statement If he condional expression nth i statrt st (1) the program co tins to execte the commands that follow the Lf statement ale Flowchart | ATLA poem re wa MATLAB commu am MATLAB progam Tiger Ase The structure of the fend conditional statement sway down to the end statement. Ifthe conditional expression is fase (0) the program skips te group of commands between the ££ and fe ‘2nd, and continues with te commands that fll te es statemet. The etserend structure ‘The if-else-ond stcture provides # mean for choosing ne troup of commands, out of «posible two groups, for exeeton (exe Fig AS). Tho ist ine san ££ satement with condnal expr: sion. IF the conditional expression ist, the progsam exces fhe ‘roup I commands beeen the 1fand the else sntemens and en Skips tothe end, Ifthe conditional expression i false, the progr saps to the e1s0 slaement apd executes the group 2 commas ‘etWeen the <2 se andthe enc sateen The eleifend structure The {f-elseif~else~cnd siture is shown in Fig. A-6, This structure includes two conditional statements (4 and el 22 £) tat 46 Appendic A Introductory MATLAB Flowchart MATLAB program t 4. comional expression Group | as MATLAB commands Group aa) Paar] MATLAB commns. Seale MATA op, make it posible o select one out of tre groups of commands for exe- ‘ition, The fit lin tan stateent with a conitional expression the conditional expeston is ru, the program executes the roup 1 commands beoween the and the 21921 salemens apd he sk to the end. If the conditional expression inthe = statement is false, the program skips tthe e1.s0i statement If the condional expres Flowchart p< 17 venta ween as (on co ea ] Rianne ut om Figure 4-6 The structure of the Lf-etseif-e1se-end conna statement sion the oi se: statement sr, the program executes the group 2 ‘commande between the sl20if and the ele sslements and then Skips to the end. I the conditional expression inthe e1se4 sate- tment fle the program skips to the o1 se salment and executes the ‘roup 3 commands between the 21se andthe end saemens. 47 Several ¢1sei¢ statements and associated groups of commands «an be add, In tis way more condition canbe included. Alo, fe flee statement is optional This means that inthe case of seer] Leet statements and no e226 astrent, i any ofthe condita ‘Satmens st, the associated commande are executed, but terme othing is excested Th genera, the sme tsk canbe accomplished by using sve elseif sttements oi f-e1seend structures. A beter progr ‘ming practice is to we the ler eto, wish makes the program es- Ter to understand, modify and debug. A.tt. Loops ‘loop i another meas to alr the Now of computer program. I loop, te execution of command, or group of commands, repeated several times consecutively. Fach round of execution called past. ach pas atleast one variable (but usualy more than ens) that i fined within the loop isasigned ane vale forend oops ln for-2na loops, the execution of a command ora group of com mands is repeated «predetermined number of dimes. The form of te Toop is shown in Fig. A. Inthe it pas = andthe computer exe wae} (eon ond igure 7: The structure of £or-end loop. cuts the commands between the for andthe ec commands. Thin, ‘he program goes back to the For commind fr the second pas. buns a aew value equl to = £ + =, andthe commands beeen he For and the ond commands are executed withthe new vale off The process repeats itself ut he last pas here = © Then the progr oes not go back othe fo, but ontinaes with he command tat le low the ena command. For example, if = 129, then there are fe oops, and the value of inthe passes i 3, 5,7, and 9. I the inc rent vale is omit is value is 1 (default) (Le, = 3:7 produces five passes with k= 3,4, 5,6, 7). ‘A prozram that stats the use of conditional statements ad loops is shown next (script ile. The progam changes the elements of 48 _ Appendix A Toroductry MATLAB. sven vector such hat elements hat are positive and are visible hy 3 fndir by 5 redoubled, Elements that ate negative but pester tan 5 te mised tothe power of 3, and al she ober element are unchanged, Ve 5, 27, -3, @, 0, -, 22, 35, 20-6, 6, &, -2, 2617 re Length @) ois | See aae aT) SE V0) >08 (zem(V (8) ,3) ==0 | xem (V (2) 5) vie) = 20¥0 teats vee) <04v() 2-5 vim) =v 0813; When the program is execute, the ftlowing new vector is displayed in the Command Window: A412 PROBLEMS ‘AL Deine the variables x and sa8¢=53, and 7. then evan (a) 2, +14s2—0822 (6) ate—2e+(F)-(2)* oy o-@) A2 Deine 1wo variables: afpho= 35%, tr= 2%, Using these variables, show tat he following igo- ‘ometic identi caect by calcalting the value ofthe let and ight sides of the equation: cosacosp = Hosta B+ xe(a-+8)) AS. Twottigonometic identities are given by Forcach par, verify thatthe identity’ comect by calculating the values oth eft and rh sides of ‘he equation, subtuing x = 172 AA Crate row vector with 1Seqully spaced elements in which the first elements 9 andthe last ele [AS Create column vector in wich the fist elements 1 the elements decrease with increments of ‘nd the Ist clement 10, (A column vector can be rested by the tanspose of row vector) | | | |

Você também pode gostar