You are on page 1of 36
7] Volkan k&sll DUNDEE 4 An Introduction to Matlab Version 2.2 David F. Griffiths Department of Mathematics The University Dundee DD1 4HN With additional material by Ulf Carlsson Department of Vehicle Engineering KTH, Stockholm, Sweden prright OIG by David F- Criiiths, Amended October, 1987 and August 2001, ‘This introduction may be distributed provided that it is not be altered in any way and that its source is properly and completely specified. Contents 9 10 un 2 13 4 MATLAB Starting Up 2.1 Windows Systems 2.2 Unix Systems 2.3 Command Line Help 24 Demos: Matlab as a Calculator Numbers & Formats ‘Variables 5.1 Variable Names Suppressing output Built-In Functions 7.1 Trigonometric Functions 7.2. Other Elementary Functions Vectors 8&1 The Colon Notation 8.2 Extracting Bits of a Vector 8.3. Column Vectors 8.4 ‘Transposing Keeping a record Plotting Elementary Functions 10.1 Plotting—Titles & Labels 10.2 Grids. . 10.3 Line Styles & Colours 10.4 Maulti-plots 10.5 Hold 10.6 Hard Copy 10.7 Subplot - 10.8 Zooming : 10.9 Formatted text on Plots 10.10Controlling Axes Keyboard Accelérators Copying to and from Word and other applications 12.1 Window Systems 12.2 Unix Systems Script Files Products, Division & Powers of Vec- tors 14.1 Sealar Product (+) 14.2 Dot Product (.#) 14.3 Dot Division of Arrays (./) - 144 Dot Power of Arrays (.~) 15 Examples in Plotting 2 16 Matrices—Two-Dimensional Arrays 16.1 Size of a matrix 16.2 Transpose of a matrix 16.3 Special Matrices 164 The Identity Matrix 16.5 Diagonal Matrices 16.6 Building Matrices 16.7 Tabulating Functions 3 16.8 Extracting Bits of Matrices 16.9 Dot product of matrices ( 16.10Matrix-vector products 3 16.11Matrix~Matrix Products 3 16.12Sparse Matrices 3 17 Systems of Linear Equations 17.1 Overdetermined system of linear equa- tions 18 Characters, Strings and Text 19 Loops 20 Logicals 20.1 While Loops 20.2 if...chen...else...end 21 Function m-files 21.1 Examples of functions 22 Further Built-in Functions 22.1 Rounding Numbers 222 The sum Function 22.3 max & min 22.4 Random Numbers 22.5 find for vectors 22.6 find for matrices 28 Plotting Surfaces 24 Timing ° 25 On-line Documentation 26 Reading and Writing Data Files 9 26.1 Formatted Files 10 26.2 Unformatted Files 27 Graphic User Interfaces 28 Command Summary 10 10 WL 12 12 13 13 4 Mu 4 4 15 6 15 16 16 1 ir 18 19 20 21 2 2 23 Py 25 26 28 28 or 28 28 20 30 31 1 MATLAB ‘¢ Matlab is an interactive system for doing nu- ‘merical computations. ‘* Anumerical analyst called Cleve Moler wrote the first version of Matlab in the 1970s, It has since evolved into a successful commercial software package. « Matlab relieves you of a lot of the mundane tasks associated with solving problems nu- merically. This allows you to spend more time thinking, and encourages you to experiment. ‘+ Matlab makes use of highly respected algo- rithms and hence you can be confident about your results. '* Powerful operations can be performed using just one or two commands. ‘+ You can build up your own set of functions for a particular application. ‘© Excellent graphics facilities are available, and the pictures can be inserted into XTX and Word documents. ‘These notes provide only a brief glimpse of the power and flexibility of the Matlab system. For a more comprehensive view we recommend the book Matlab Guide D4. Higham & N.J. Higham SIAM Philadelphia, 2000, ISBN: 0.39871-469-9 2 Starting Up 2.1 Windows Systems (On Windows systems MATLAB is started by double- clicking the MATLAB icon on the desktop or by selecting MATLAB from the start ment. ‘The starting procedure takes the user to the Com- mand window where the Command line is indicated with '>>', Used in the calculator mode all Matlab commande are entered to the command line from the keyboard. ‘Matlab can be used in a number of different ways or modes; a8 en advanced calculator in the calculator rode, in «igh level programming language mode ‘and a¢ a subroutine called from a C-program. More information on the first two of these modes is given below. Help and information on Matlab commands can be found in several ways, from the command line by using the "help ‘topic’ command (see below), ‘+ from the separate Help window found under the Help menu or ‘© from the Matlab helpdesk stored on disk or on a CD-ROM. Another useful facility is to use the "Lookfor keyword’ ‘command, which searches the help files for the key- word. See Exercise 16.1 (page 17) for an example ofits use 2.2 Unix Systems + You should have a directory reserved for sav- ing files associated with Matlab, Create such a directory (mkdir) if you do not have one. Change into this directory (cd) «Start up anew xterm window (do xterm &in the existing xterm window) Launch Matlab in one of the xterm windows with the command matlab After a short pause, the logo will be shown followed by >» where >> is the Matlab prompt. ‘Type quit at any time to exit from Mat- lab, 2.3 Command Line Help Help is available from the command line prompt. ‘Type help help for “help” (which gives a brief syn- opsis of the help system), help for a list of topics. ‘The first few lines of this read HELP topics matlab /general - General purpose commands matlab/ops - Operators and special char... matlab/lang - Programming language const. matlab/elnat - Elementary matrices and mi matlab/elfun - Elementary math functions. stlab/epecfun ~ Specialized math functions. (teuncated lines are shown with ...). Then to ob- tain help on “Elementary math functions”, for instance, type >> help elfua ‘This gives rather « lot of information so, in order to see the informetion one screenful at a time, first issue the command more on, Le., >> help elfua Hit any key to progress to the next page of information. 2.4 Demos Demonstrations are invaluable since they give an ind cation of Matlabs capabilities. A comprehensive set are available by typing the command >> dene ( Warning: this will clear the values of all current vari ables.) 3 Matlab as a Calculator ‘The basic arithmetic operators are + - * / ~ and these are used in conjunction with brackets: ( ). Thesymbol “is used to get exponents (Powers): 2"4=16. ‘You should type in commands shown following ‘the prompt: >>. o> 2+ 3/485 5.7500 Is this calculation 2 + 3/¢4*5) or 2 + (2/4)+5? Mat- lab works according to the Priorities: 1, quantities in brackets, 2, powers2+3°292 79> 11, 3. + /, working left to right (3+4/5=12/5), 4. + =, working left to right (3+4-5=7-5), ‘Thus, the earlier calculation was for 2 + (3/4)45 by priority 3. 4 Numbers & Formats Matlab recognizes several different kinds of numbers Type __| Examples, Integer | 1362, -217897 Real | 1.284, —10.76 Complex | 3.21- 4.38 (§= ¥=T. Inf Infinity (result of dividing by 0) NaN__| Not a Number, 0/0 " notation is used for very large or very small numbers: 4. 2412603 = -1.8412 x 10° = -1941.2 =4,24126-01 = -1.3412 x 10"! = -0.19412 {All computations in MATLAB are done in double pre- cision, which means about 15 significant figures. The format—how Matlab prints numbers—is controlled by the “format” command. Type help format for full lst. Should you wish to switch back to the default format then format will suffice. ‘The command | format compact: is also useful in that it suppresses blank lines in the output thus allowing more information to be displayed. Command Example of Output >oformat short | 31.4162(d-decimal places) >>tormat short e | 3.1416e+01 >>format long e | 3. 1415926535897930+01 >>format short | 31.4162(4-decimal places) >>format_bank | 31.42(2-~decimal places) 5 Variables o> 274 “13 >> anes 65 ‘The recult of the first calculation is labelled “ans” by Matlab and is used in the second calculation where its value is changed. Wecan use our own names to store numbers: doe 8-24 13 doy = x05 r 65 so that x has the value -13 and y = —65, These can be used in subsequent calculations. These are examples of assignment statements: values are assigned to variables. Each variable must be assigned a value before it may be used on the right of an assignment statement. 5.1 Variable Names Legal names consist of any combination of letters and digits, starting with a letter. These are allowable: NetCost, Left2Pay, x3, X3, 2255 These are not allowable: Net-Cost, 2pay, Ux, Ceign Use names that reflect the values they represent. Special names: you should avoid using ops ~ 2.22040-16 = 27% (The largest number such that 1 + eps is indistinguishable from 1) and pi = 3.14159. Ifyou wish to do arithmetic with complex numbers,both i and j have the value V=T unless you change them >> ij, ina ans = 0 + 1.00008 ans = 0 + 1.00003 i =3 6 Suppressing output (One often does not want to see the result of intermedi- ate calculations—terminate the assignment statement or expression with semi-colon the value of x is hidden. Note also we can place several statements on one line, separated by commas or semi- colons. Exercise 6.1 In each case find the value of the expres- sion in Matlab and ezplain precively the order in which the calculation was performed. i) 2/363 iv) 304-5-262-3 (2/37205)*(3-473)"2_ vi) 34(344-26572-8) 7 Built-In Functions 7.1 Trigonometric Functions ‘Those known to Matlab are ‘and their arguments should be in radians, ‘eg. to work out the coordinates of a point on a circle of| radius 5 centred at the origin and having an elevation 30° = 1/6 radians: >> x = Sacos(pi/6), y = Sesin(pi/6) 4.3301 ye 2.5000 ‘The inverse trig functions are called asin, acos, atan (as opposed to the usual arcsin or sin etc.). The result Is in radians, >> acos( pile ane = 0.5236 7.2 Other Elementary Functions ‘These include art, exp, log, Logid >> x29 >> sqrt z) ,exp(x) , Log (agrt (x)) ,Logio(x"2+6) a 8, 10816+03, ssid the inverse function is Log: >> format long 9, oxpClog(9)), Logexp(9)) fans = 9.0000000000000026+00 ans = 9 >> format short and we see a tiny rounding error in the first calculation. 1ogt0 gives logs to the base 10. A more complete list of elementary functions is given in Table 2 on page 32. 8 Vectors ‘These come in two flavours and we shall first describe row vectors: they are lists of numbers separated by ek ‘ther commas or spaces. The number of entries is known, as the “length” of the vector and the entries are often referred to as “elements” or “components” of the vec- tor-The entries must be enclosed in square brackets, >> ve C1 3, sare(s)] 1.0000 >> Leagenv) 3 3.0000 2.2361 Spaces can be vitally important: >> v2 = (36 4 5] 2 rae o> v3 = (3 +4 5] Be a Chet We can do certain arithmetic operations with vectors of the same length, such as v and v3 in the previous section, pve 4.0000 7.0000 7.2361, >> vd = Bey we 3.0000 9.0000 6.7082 >> vB = 2ev ~ev3 mee 7.0000 6.0000 -10.5279 >ovty2 277 Error using —=> + Matrix dimensions aust agré le. the error is due to v and v2 having different lengths. A vector may be multiplied by a scalar (a number— see v4 above), or added/subtracted to another vector of the same length. The operations are carried out elementwise ‘We can bulld row vectors from existing ones: >w = 423), 2-89) >> ed = [2ez,-u], sort (ed) ipo 2S: oe) 1 3 2 1 18 Notice the. last to ascending ord WE Gan EES Ghange or look at the value of parteular entries >> ¥(Q) = -2, ¥@) a a : = 8.1 The Colon Notation ‘This is a shorteut for producing row vectors: > 14 More generally a:b : © produces a vector of entries starting with the value a, incrementing by the value 6 until it gets to ¢ (it will not produce a value beyond c). This is why 1:-1 produced the empty vector [1 >> 0.32:0.1:0.6 0.3200 0.4200 0.6200 >> -1.4:-0.3:-2 “1.4000 1.7000 -2.0000 8.2 Extracting Bits of a Vector p> 8 = (12:6, -1:-2:-71 — ee aa ‘To get the rd to 6th entries: >> 16(3:6) 5 5 To get alternate entries: >> x6(1:2:7) Hee What does =5(6:-2:1) give? Ses help colon for a fuller descri 8.3 Column Vectors These have similar constructs to row defining them, entries are separated by vectors. When or “newlines” >> = C1; 3; agrt(6)] 1.0000 3.0000 2.2361 > a= (3 4 8 ee 3 4 5 D> eB = 4c - 342 ee 7.0000 ; 6.0000 -10.5279 so column vectors may be added or subtracted pro- vided that they have the same length. 8.4 Transposing We can convert a row vector into a column vector (and vice versa) by 8 process called transposing—denated by > we, ce! 1.0000 3.0000 2.2361 \ 1.0000 3.0000 pots tect t- 3.0000 4.0000 >> T= Sevr-ave te 2.2361 7.472 3.0000 16.0000 10.5279 Ifx is a compler vector, then x? gives the complex con- Sugate transpose of x: o> x= [1v3i, 2-28) 1.0000 + 3.00003, > x 1.0000 = 3.00008, 2.0000 + 2.00005 2.0000 ~ 2.00004 Note that the components of x were defined without 4 operator; this means of defining complex numbers works even When the variable 4 already has a numeric value, To obtain the plain transpose of a complex num- ber use .” as in 1.0000 + 3.00008 2.0000 - 2.00008 9 Keeping a record Issuing the command >> diary ayeessicn wil cause all subsequent text that appesrs onthe screen {o be stved to the fle aysceston lated In the direc: tory in which Mtiay was involed. You tay woe exy legal filename except the names an and off. The record may be terminated by .on may be edited with emacs to remove Ifyou wish to quit Matlab midway through a calcula- tion so a8 to continue ata later stage: >> save thisseasion will save the current values of all variables to a filo called thissession.nat. This file cannot be edited. ‘When you next startup Matlab, type >> load thiasession and the computation can be resumed where you left off A list of variables used in the current session may be ‘seen with >> whos See help vhos and help save. >> vhos None Size Elements Bytes Density Complex ans byt 1 8 Ful No vitys 3 m4 Full Yo wiiy22 16 Full Ho wi22 16 Full Wo v8 ttys 3 Full No vettys 3 Full Yo xibytt 8 Full Ko yibid 8 Full No Grand total is 16 elements using 128 bytes 10 Plotting Elementary Func- tions Suppose we wish to plot a graph of y = sins for 0-< <1. We do thie by sampling the function at a sufficiently large number of points and then joining up the peints (=, ») by straight lines. Suppose we take N+ 1 points equally spaced a distance h apart: D> Ne 10; ho AMM; x = Obst; defines the set of points x =0,h,2h,...,1 corresponding y values are computed by Al. The >> y = sin@epirx); and finally, we can plot the points with >> ploete,y) ‘The result is shown in Figure 1, whore it is clear that the value of NV is too small inSrz for 0 > N= 100; b= A/N; x = Ok: 1; >> y = sin(Sepiex); plot(x.y) wwe get the picture shown in Figure 2. 10.1 Plotting—Titles & Labels To put a title and Isbel the axes, we use >> title(*Graph of y = sin(3pi x)") >> xlabel ('x axis’) >> ylabel (y-axis?) ‘The strings enclosed in single quotes, can be anything of our choosing. Some simple IXTpX commands are available for formatting mathematical expressions and Greek characters—see Section 10.9. Figure 2: Graph of y = sin3nz for 0< x <1 using h= 001 10.2 Grids A dotted grid may be added by >> grid ‘This can be removed using either grid again, or grid oft. 10.3 Line Styles & Colours ‘The default is to plot solid lines. A solid vhite line is produced by > ‘The third argument is a string whose first character specifies the colour(optional) and the second the line style, The options for colours and styles ar >> plot(e.y, lous Cine Ses 7 yellow Polat 2 agente o circle ¢ gan x xmark x red + plus & gen = - sold B bie + star white dotted Black —~, dashdot = dashed ‘The number of available plot symbols is wider than shown in this table. Use help plot to obtain s full list, See also help shapes. 10.4 Multi-plots Several graphs may be drawn on the same figure as in ”) >> plot (x,y, "¥-?,x,cos Sepiex) , ‘A descriptive legend may be included with, >> Legend(?Sin curve’, Cos curve?) which will give a list of line-styles, as they appeared im the plot command, followed by a brief description. Matlab fits the legend in a suitable position, so as not ‘to conceal the graphs whenever possible. For further information do help plot etc. ‘The result of the commands >> plot(x,y,?#-" .x,cos(apiex) ,’g-~7) >> legend(?Sin curve’ ,’Cos curve?) >> title(’Multi-plot *) >> xlabel (x axis’), ylabel(y axis’) >> grid is shown in Figure 3. The legend may be moved man- ually by dragging it with the mouse, Figure 3: Graph of y = sin 3nz and y = cos3xz for O< 2 <1 using A= 0.01 10.5 Hold A call to plot clears the graphics window before plot- ting the current graph. This is not convenient if we wish to add further graphics to the figure st some later stage. To stop the window being cleared: >> plottx,y,"¥), held >> plettx,y, gx), Bold off “old on” holds’ the current picture; “held off" re- leases it (but does not clear the window, which can be done with elf). “hold on its own toggles the hold state. 10.6 Hard Copy ‘To obtain a printed copy select [Print] from the [File ‘menu on the Figure toolbar. ‘Alternatively one can save a figure to a file for later printing (or editing). A number of formats is avail able (use help print to obtain a list). Tb save a file in “Bneapoulated PostScript” format, issue the Matlab command print ~deps figt which will save a copy of the image in a file called Ligh eps, 10.7 Subplot ‘The graphles window may be split into an m xn array ‘of emaller windows into which we may plot one or more graphs. The windows are counted 1 to mn row-wise, starting from the top left. Both hold and grid work oa the current subplot. >> subplot (221), plot (x,y) >> xlabel(’x?),ylabel(’sin 3 pi x’) >> subplot (222) , ‘plot (x,cos(epiex)) >> alabel(?x’), ylabel('cos 3 pi x’) >> subplot (223), plot (x, sin(6epi#x)) >> xdabel (x?) ylabel (ein 6 pi x!) >> subplot (224) , ‘plot (x,costSepiex)) >> alabel(?x) ylabel (cos 6 pi x’) subplot (221) (or subplet(2,2, 1)) specifies that the window should be split into a 2 x 2 array and we select the first subwindow. 10.8 Zooming We often need to “zoom in’ on some portion of a plot in order to see more detal. This i easily achieved using the command Pointing the mouse to the relevant position on the plot and clicking the left mouse button will zoom in by a factor of two, This may be repeated to any desired level. Clicking the right mouse button will zoom out by a factor of two. Holding down the left mouse button and dragging the mouse will cause a rectangle to be outlined. Releasing ‘the button causes the contents of the rectangle to fill, the window. zoom off turns off the zoom capability. Exercise 10.1 Draw graphs of the functions pes cas os for 0< = <2 on the same window. Use the zoom fox cility to determine the point of intersection of the two curves (and, hence, the root of = = cos.) to two signif. icant figures. ‘The command cl clears the current figure while close 4 will close the window labelled “Figure 1". To open ‘new figure window type figure or, to get a wiadow labelled “Figure 9", for instance, type figure (9). If “Figure 9" already exists, this command will bring this window to the foreground and the result subsequent plotting commands will be drawn on it. 10.9 Formatted text on Plots It is possible to change to format of text on plots so as to increase or decrease its size and also to typeset simple mathematical expressions (in TEX form). Wo shall give two illustrations, First we plot the first, 100 terms in the sequence (4) given by 2, = (1+ 4)" and then graph the function $(2) = 2° sin%(Gn2) On the interval -1 <2 <1. The commands >> sot (0, ’Detaultaxesfonteize’,16); >> m= 11100; x = (14t./n) >> subplot (211) >> plotta,x,”.”, [0 maxCa)] ,exp(1)*(1 10,.. 'a-1, aarkeraize’ 2) >> title (aa = (1+1/a)"a", 'fontaize? ,12) >> xlabel('n’), ylabel(?x_n') >> legend(?x_a",?y = o"t = 2.71828...7,4) >> orate >> subplot (212) > 2:2; y = x.°9.exin(Sepien).“2; >> plote,y,’Linewiaeh ,2) >> legend@'y = x"30in"2 3\pi x4) > elabel 2") produce the graph shown below, ‘The salient features ofthese commands are 1. The first line increasts the sizeof the default font size used for the axis labels, legends and titles. 2. The size of the plot symbol "is changed from the default (6) to size 8 by the additional string followed by value “/markersize’ 2". 3. The strings ‘xn are formatted as» to give sub- scripts while 'x~3 leads to superscripts x’. ‘Note also that sin?3nz translates into the Matlab command sin(3epiex).~2—the positon of the exponent is different. 4. Greek characters a, the stings "\alpha’ Noses’, \Oaege’. the integral symbol: Js produced by Vint 5. The thickness ofthe line used in the lover graph is changed from its default value (0.5) to 2. 6. Use help legend to determine the meaning of the last argument in the Legend commands, One can determine the current value of any plot prop- ety by fst obtaining its “handle number” and then using the get command such as >> handle = plot (x.y,".7) >> get (handle, ’arkersize’) 6 Experiment also with set (handle) (which will list possible values for each property) and set (handle, ’mark Also, all plot properties can be edited from the Figure window by selecting the [Tools] menu from the tool- bar. For instance, to change the Linevidth of a graph, first select the curve by double clicking (it should then ‘change its appearance) and then select| Line Properties. from the [Tools]. This will pop_up a dialogue window from which the width, colour, stle,...of the curve may be changed, 10.10 Controlling Axes Once a plot has been created in the graphics window Figure 4: The effect of changing the axes of a plot. pr followed by T will recall the most recent command starting with pr. Once a command has been recalled, it may be edited (changed). You can use + and — to move backwards and forwards through the line, characters may be in- serted by typing at the current cursor pesition or deleted ‘sing the Del key. This is most commonly used when Jong command lines have been mistyped or when you want to re-execute a command that is very similar to ‘one used previously. ‘The following emacs-like commands may also be used: move to start of line move to end of line move forwards one character move backwards one character delete character under the cursor catrl @ catrl ¢ catrl £ catrl b eatrl d you may wish to change the range of = and y values shown on the picture >> elf, N= 100; b= 1/1; x = O:: >> y = sin(Qepiex); plotx.y) >> axis((-0.5 1.5 “1.2 1.2]), grid The axis command has four parameters, the first two are the minimum and maximum values of to use on the axis and the last two are the minimum and maxi- ‘mum values of y. Note the square brackets. The result of these commands is shown in Figure 4. Look at belp axis and experiment with the commands axis equal, aris verb, axis aquare, axie normal, axis tight in any order. 11 Keyboard Accelerators (One can recall previous Matlab commands by using the T and | cursor keys. Repeatedly pressing { will review the previous commands (most recent first) and, if you ‘want to re-execute the command, simply press the re- turn key. ‘To recall the most recent command starting with p, say, type p at the prompt followed by f. Similarly, typing (Once you have the command in the required form, press retura Exercise 11.1 Type in the commands >> xe 110.401; >> plot(e,sin(piex),1e-") >> hold on >> plot (x, cos(pisx) ,*x-") Now use the cursor keys with suitable editing to execute >> x= -1:0.05:4; >> plot (x, sin(2rpisx), 7) >> plot(x,coa(2epiex),’z-.'), hold oft 12 Copying to and from Word and other applications ‘There are many situations where one wants to copy the output resulting from a Matlab command (or com- mands) into a Windows application such as Word or into a Unix file editor such as “emacs” or “vi”, 12.1 Window Systems Copying material is made possible on the Windows op- crating system by using the Windows clipboard, ‘Also, pictures can be exported to files in a number of alternative formats such as encapsulated postscript fr- tat or in jpeg format. Matlab is so frequently used as an analysis tool that many manufacturers of measure- ment systems and software find it convenient to pro- Vide interfaces to Matlab which make it possible, for instance, to import measured data directly into a nat Matlab file (se2 Load and save in Section 9) Example 12.1 Copying a figure into Word. Diagrams prepared in Matlab are easly exported to other Windows applications such as Word. Suppose 4 plot ofthe functions sin(2ne) and sin(2rft + /), with f= 10, is needed in «report written in Word We create a time vector, ¢, with 800 points distributed cover 5 periods and then evaluate and plot the two fune- tion vectors. > # = [4:1:500]/500/20; a): 2 = sin(2epieteerpi/4); dp plottsyty?=",t,y2,!~") 5 >> axis([0 0.05 “1.5 1.51); >> grid In order to copy the plot into a Word document ‘¢ Select “Copy Figure” under the [Edit the figure windows toolbar. ‘ Switch to the Word application if it is already running, otherwise open a Word document. ‘+ Place the cursor In the desired position in the document and select “Paste” under the “Edit” ments in the Word tool bar. 12.2 Unix Systems In order to carry out the following exercise, you should have Matlab running in one window and either Emacs or Vi running in another, ‘To copy material from one window to another, (here “Bneans click Left Mouse Button, First select the material to copy by ‘material you want and then either dragging the mouse (with the buttom down) to highlight the text, or TEat the end of the material. Next move the mouse into the other window and {at the location you want the text to appear. Finally, click the 3. When copying from another application Into Matlab you can only copy material to the prompt line. On Unix systems figures are normally saved in files (see Section 10.6) which are then imported into other doc- uments. 10 13 Script Files Script files are normal ASCII (text) files that contain Matlab commands. It is essential that such files have names having an extension .2 (e., Exercised.) and, for this reason, they are commonly known as miles ‘The commands in this file may then be executed using >> Exercises Note: the command does not include the file name ex- tension «2. It is only the output from the commands (and not the commands themselves) that are displayed on the screen. Script files are created with your favourite editor under Unix while, under Windows, click on the “New Docu- ment" icon at the top left of the main Matlab window to pop up a new window showing the “Mcfile Editor” ‘Type in your commands and then save (to a file with +m extension), ‘To see the commands in the command window prior to their execution: >> echo on and echo off will turn echoing off. ‘Any text that follows on a line is iguoced. The main Purpose of this facility is to enable comments to be included in the file to describe its purpose ‘To see what mfiles you have in your current directory, >> what Exercise 13.1 1. Type in the commands from §10.7 into a fle called exsub.m 2 Use what to check that the file is in the correct 3. Use the command type ezsub to see the contents of the file. 4. Execute these commands, See §21 for the related topic of function files. 14 Products, Division & Pow- ers of Vectors 14.1. Scalar Product (*) ‘We shall describe two ways in which a méaning may be attributed to the product of two vectors. In both cases ‘the vectors concerned must have the same length. ‘The first product is the standard scalar product. Sup- pose that w and » are two vectors of length n, u being row vector and y a column vector: a Ped Cee : ‘The scalar product is defined by multiplying the corze- sponding elements together and adding the results to sive a single number (scalar). ue Dom For example, if u = (10, —11,12], and » = on ch 10 x20 + (11) x (—21) + 12x (—22) = 167. then n =3 and We can perform this product in Matlab by >> w= (10, “11, 12), v= (20; -24; -22) >> prod = uty | row times column vector Suppose we also define a row vector w and a column vector 2 by >> (2,4, 31, = (7; 6; 8) 2g gal Si 7 6 el and we wish to form the scalar products of u with w and v with 2. 77 Error using ==> + Taner matrix dinensions aust agree an error results because w is not a column vector. Recall from page § that transposing (with ’) turns column ‘vectors into row vectors and vice versa. So, to form the scalar product of two row vectors or two column vectors, >> usw) Lu Bw are row vectors 45 >> uw? hu is a row vector 365 >> viez hy kz are column vectors 96 ‘We shall refer to the Euclidean length of a vector as the norm of a vector; itis denoted by the symbol lel and defined by tl yr, where n is its dimension. This can be computed in Matlab in one of two ways: >> [sqrt (uu), nora(u)] 19.1050 19.1050 where nora is a built-in Matlab function that accepts a vector as input and delivers a scalar as output. It can ‘also be used to compute other norms: help norm. u Exercise 14.1 The angle, 8, between two column vec- tors z ond y 18 defined by Tet ul Use this formula to determine the cosine of the angle between 2,1 1,2,3)' and y= Hence find the angle in degrees. 14.2 Dot Product (.*) ‘The second way of forming the product of two vectors of the same length is known as the Hadamard product, It is not often used in Mathematics but is an invalu- able Matlab feature. It involves vectors of the same type. If and y are two vectors of the same type (both row vectors or both column vectors), the mathematical definition of this product, which we shall call the dot product, is the vector having the components fuer, uatn, tint) ‘The result is a vector of the same length and type as and y. Thus, ve simply multiply the corresponding flements of two vectors. In Matlab, the product ic computed with the opera: tor .* and, using the vectors u, v, v, 2 defined on age 11, 20 -11 36 200 231 -264 140 -126 -110 ‘200 291 -264 Example 14.1 Tatulate the function y = zsinrz for = =0,0.25, ‘It is easiar to deal with column vectors 80 we first define ‘a vector of z-values: (see Transposing: §8.4) >> x = (0:0.25:1)"; ‘To evaluate y we have to multiply each element of the vector z by the corresponding element of the vector 0.7500 x 0.7071 = 0.5303 1,0000 x 0.0000 = 0.0000 To camry this out in Matlab: 0.1768 9.5000 0.5303, 2.0000 Note: a) the use of pi, b) x and sin(pi+x) are both column vectors (the sia function is applied to each el- cement of the vector). Thus, the dot product of these is also a column vector. 14.3 Dot Division of-Arrays (./) ‘Thore is no mathematical definition for the division of one vector by another. However, in Matlab, the opeca- tor ./ isdefined to give element by element division—it is therefore only defined for vectors of the same size and type. >> a 1:5, b= 6:10, a/o i ee oe 6 0.1667 0.2857 0.3750 0.4444 0.5000 > ala 7 0 foe. 10, te Warning: Divide by zero 0.5000 -2.0000 Inf 4.0000 2.5000 ‘The previous calculation required division by 0—notice the Inf, denoting infinity, in the answer. >> awd -24, ans./e “18-1000 «1228 Warning: Divide by zero 9 10 MN 12 43, Here we are warned about 0/0—giving a NaN (Not a Number). Example 14.2 Estimate the limit lim ‘The idea is to observe the behaviour of the ratio #22 for a sequence of values of x that approach zero. Sip- ‘pose that we choose the sequence defined by the column vector >> x = [0.1; 0.01; 0.001; 0.0001) then 12 >> sin(piex)./x 3.0902 3.1411 3.1416 3.1416 which suggests that the values approach x, To get a better impression, we subtract the value of 7 from each, entry in the output and, to display more decimal places, wwe change the format >> forzat long >> ans pi ~0.05142270984032 =0.00081674577696 0.00000616771023 0.00000005167713, Can you explain the pattern revealed in these numbers? We also need to use ./ to compute a scalar divided by vector: >> te 277 Error using ==> / Matrix dimensions must agre >> L/e 10 100 1000-10000 $0 1./x works, but 1/x does not. 14.4 Dot Power of Arrays (.~) “To square each ofthe elements ofa vector we could, for example, do u.eu. However, a neater way isto use the “* opeentor >> ace 400 121148 100 121 144 ud 10000 14641 20736 ro) 2.8000 -11.0000 1.3333 Recall that powers (.~ im this case) are done firs, before any other arithmetic operation, 15 Examples in Plotting Example 16.1 Draw grophs ofthe functions for0< =< 10, >> x = 0:0.1:10; >> y = sine) ./x; >> subplot (221), plot (x,y), title? (i)’) Warning: Divide by zero >> w= 1 /Get) 72 + >> subplot (222) ,plot(x,u), title(? (1i)*) Warning: Divide by zero Dov = (ADH). JD; >> subplot (223) ,plot(x,w) ,titie("(4ii)") Warning: Divide by zero >> w= ((10-2).7G/3)=1) . /sqrt 4x2); Werning: Divide by zero >> subplot (224) ,plot(x,) ,title( (iv)’) peecié Note the repeated use of the “dot” operators. Experiment by changing the axes (page 9), grids (page 7 ‘and hold(page 7). subplot (222) ,axis([0 10 0 10]) erie grid hold on plot(z,v, > »), hold off, plot(x,y,!:1) Exercise 15.1 Enter the vectors Z= (6.24, V=[3,-2,3,0), 3 3 —4 2 w Ale eae 6 7 into Matlab. 1. Which of the products ev, Vow, UWV?, WoW; WeZ?, U.e¥ Dev, Wel, WeZ, Ue, WaZ, View fs legal? State whether the legal products are row or column vectors and give the values of the legal results, , 13 2 Tabulate the functions 2? +9) sin xz? ond = sin? r2/(z"? +3) fort =0,0.2,...,10. Hence, tabulate the func: tion (2? +9) sin na? sin? nz E43) Plot a groph of w over the range 0 <= < 10. 16 Matrices—Two-Dimensional Arrays Row and Column vectors are special cases of matrices. ‘An m xn matrix is a rectangular array of numbers hhaving m rows and columns. [t is usual in a math- ematical setting to include the matrix in either round ‘or square brackets—we shall use square ones. For ex- ample, when m = 2,n = 3 we have a 2 3 matrix such ‘To enter such an matrix into Matlab we type it in row by row using the same syntax as for vectors: 5 1 t 2 9 = > A167 9 1-3-7] ee 0 =a 7, Rows may be separated by semi-colons rather than a new line: >> B= (125; 905) oe Bae fe 0 >> = (0, 1; 3, -2: 4, 2 ie Oe 32 40; 11:2:20) aoe 0. +10 16 aT igi So A and B are 2x 3 matrices, ¢ is 3 x 2 and Dis 3 x 5. In this context, a row vector is a 1x n matrix and a ‘column vector a.m x 1 matrix, 16.1 Size of a matrix ‘We can get the size (dimensions) of a matrix with the command size >> size(A), size(x) a8 et >> size(ans) er So Ais 2x3 and x is $x 1 (a column vector). The last command size (ans) shows that the velue returned by ‘size is iteelf « 1x2 matrix (a row vector). We ean save the results for use in subsequent calculations. >> (x e] = size(a'), $= sizeca’) 16.2 Transpose of a matrix ‘Transposing a vector changes It from a row to a column, vector and vice versa (eee §8.4). The extension of this to matrices is that transposing interchanges rows with the corresponding columns: the Ist row becomes the Ist column, and so on. Bile rae) petrp juste, A et Ae A 25 A ar 5 10 49 >> size(D), size(D’) al es Cee 16.3 Special Matrices Matlab provides a number of useful built-in matrices of any desired size. ones(a,n) gives an m xn matrix of 1's, >> P= onea(2,3) Pe 1 White ae i seed dott zeros (a,n) gives an m x n matrix of O's, >> Z = zeros(2,3), zeros(size(P’)) ee 0 08 40 Ol 0 cio) oo oo oo ‘The second command illustrates how we can construct 4 matrix based on the size of an existing one, Try ones (size(D)). : ‘An nxn matrix that bas the same number of rows and columns and is called a square matrix ‘A matrix is said to be symmetric if itis equal to its transpose (ie. itis unchanged by transpesition} o> $= (2-10; 12-1; 0-121, se Qrai pies feet Gist >> sess! se = to) 1 bossagte> up o 1 2 > st oe 0) . 0-0) joo 20 16.4 The Identity Matrix ‘The n x n identity matrix is a matrix of zeros except for having ones along its leading diagonal (top left to bottom right). This is called eye (a) in Matlab (since mathematically it is usually denoted by J) >> T= eye(3), x= (8; 4; 1], Tnx T+ o8 1 eae Notice that multiplying the 3 x 1 vector x by the 3 x 3 Jdentity T has no effect (it is like multiplying a number by 1). 16.5 Diagonal Matrices ‘A diagonal matrix is similar to the identity matrix ex- cept that its diagonal entries are not necessarily equal a “300 v= [Geo] 002 is a 3x3 diagonal matrix. To construct this in Matlab, we could either type it in directly 4 >> D = [-300; 040; 002) D- S8iec 0 f20 Ob eo: frsseec ears Dut this becomes impractical when the dimension is large (e.g; a 100 x 100 diagonal matrix). We then use the diag function. We first. define a vector d, say, con- taining the values of the diagonal entries (in order) then iag(d) gives the required matrix. >> d= (342), D= diagta) as S Behe D- ©3020 Oe 4 0 ons ora On the other hand, if A is any matrix, the command iag(A) extracts its diagonal entries: Fs (0187; 3-2-42; 4211) Fe Ue $0242 fee ait >> diag) ° -2 a Notice that the matrix does not have to be square. 16.6 Building Matrices It is often convenient to build large matrices from smaller >> o=[0. 1; 3-25 4 20; xe[Bs-4:10; > G= (Cx) Ge Cle 4c sd a eat >> A,B, H= CA; BI ie 5 Galan’ eee ee B= Sica Oru aaa 1 Sete wie ee Oo Os ‘90 we have added an extra column (x) to ¢ in order to form G and have stacked A and B on top of each other to form fi. 15 >> J= [hs4; §:8; 9:12; 2005 4] es Pe ase ote tee 9 104 42 0 braced >> K = ( diagt:4) J; 3° zerosc4,4)] ke TPE LG aes CEES fat aie hawt Mat ear po 0 0 3 0 9 10 11 12 o 0 0 See were 15 92 0000 261 00000 $2711 8.07 0 0-0 4812 40000 ‘The command spy(K) will produce a graphical display ‘of the location of the nonzero entries in X (it will also sive a value for nz—the number of nonzero entries): >> spy, grid 16.7 Tabulating Functions ‘This has been addressed in earlir sections but we are ‘ow in a position to produce a more suitable table for. mat, Example 16.1 Tabulate the functionsy = 4sin3z ond Bsin dz for = =0,0.1,0.2,...,0.5. >> x = 0:0.1:0.8; >> y = 4esin(3ex); u = Sesin(4ex); >> tx yw) ° ° ° 0.1000 1.1821 1.1683 0.2000 2.2586. 2.1521, 0.3000 3.1333 2.7961 0.4000 3.7282 2.9987 0.5000 3.9900 2.7279 Note the use of transpose (?) to get column vectors. (we could replace the last command by (x; y3 wil’) We could also have done this more directly: >> x = (0:0.1:0.5)"; >> Gr desin(Sex) Sesin(4ex)] 16.8 Extracting Bits of Matrices We may extract sections from’ matrix in much the same way as for a vector (page 5). Bach element of a matric is indexed according to which row and column it belongs to. The entry in the ith row and jth column is denoted mathematically by A, and, in Matlab, by AG, 3). So 3 ce 20 >> JG) 1 >> 3@,3) 7 >> 14,3) 5 >> 14,5) 797 Index excoeds matrix dimensions. >In) IG +6 a fea es fe 7 8 Seid Ai, a (igh OP uses >> IGA) = 3G,1) ~ 394,20 oe Sr ee Geet. e do it hia a0) 4 In the following examples we extract |) the Srd column, fi) the 2nd and 3rd columns, ii) the 4th row, and iv) the “central” 2.x 2 matrix. See §8.1 % 3rd column > IG,3) % columns 2 to 3 10 at Oa >> 34,2) % 4th row Tara See >> J(2:3,2:3) rows 2 to 3k cols 2 to 3 C7 10 1t ‘Thus, : om its own refers to the entire column or row depending on whether it isthe first or the second index. 16.9 Dot product of matrices (.*) ‘The dot product works as for vectors: corresponding elements are multiplied together—so the matrices in- volved must have the same size. > AB i Serer) eras. 445 eet ee >> hac 27 Error using ==> Matrix dimensions must agree >> hac? 2 6 ° 36 1 “14 16.10 Matrix—vector products ‘We vura next to the definition of the product of a matrix with a vector. This product is only defined for column vectors that have the same number of entries as the ‘matrix has columns. So, if A is an m x n matrix and 2 is a column vector of length n, then the matrix-vector Az is legal. ‘An m x n matrix times ann x 1 matrix + am x1 matrix. We visualise A as being made up of m row vectors stacked on top of each other, then the product cor- responds to taking the scalar product (See §14.1) of ‘each row of A with the vector 2: ‘The result is a column iseation8: Seco f=] as | sxsttx(g 49x 1b E Dx CM ECD AA a 3 It is somewhat easier in Matlab: al ® “4 1 D> A= (579; 1-3 a= >> dex a 13 1) > (mx) (m{n) times (| >> ek 77? Error using ==> + Inner matrix dimensions must agre Unlike multiplication in arithmetic, Avx is not the same as xh 16 16.11 Matrix-Matrix Products To form the product of an mx n matrix A and an p matrix B, written as AB, we visualise the first matrix (A) as being composed of m row vectors of length stacked on top of each other while the second (B) is vi- sualised as being made up of p column vectors of length = =| =< » columns ‘The entry in the ith row and jth column of the product is then the scalarproduct of the ith row of A with the jth column of B. The product is an m x p matrix: P) > (mx) rm) times (7 (ms ‘Check that you understand what is meant by working out the following examples by hand and comparing with the Matlab answers. >> A= (5 7 9; 1-3-7) ie Een ieogad 1 igh 7 >> Be (0, 1; 3, -2; 4, 2 Be one 32 ieeea >> = AB c= ae a ore >> D = Beh De i827 is ara am 2 >> B= Ba? Es 87-37 e+ Wo see that E = C’ suggesting that (acBy = BA" Why s Bx A.a3 x3 matrix while Ae B is 2x2? Exercise 16.1 [t is often necessary to factorize a mo- tris, e9., A= BO or A= S™XS where the factors are required to have specific properties. Use the ‘tookfor keyword” command to make a list of factorizations com- mands in Matlab 16.12 Sparse Matrices Matlab has powerful techniques for handling sparse ma- trices — these are generally large matrices (to make the extra work involved worthwhile) that have only a very small proportion of non-zero entries. Example 16.2 Create a sparse 5 x 4 matric S having only 3 non-zero values: Si,2 = 10, Sa,a = 11 and Ss.4 12 We first create 3 vectors containing the i-index, the j- index and the corresponding values of each term and we then use the sparse command, p> im Uh, 3, 1: j= (2.9.4; >> v= [10 11 12]; >> $= sparse (i,j,¥) s- 4.2) 10 G3) 1 6,4) 12 > T+ fu1(s) Ts o 0 0 0 Gate ey Giese est Teen) oe 0d 0. Disoi 10.7 ia ‘The matrix T is a “full” version of the sparse matrix S. Example 16.8 Develop Matlab code to create, for any given value of n, the sparse (tridiagonal) matrix We define three coum vectors, one for each “diago- nal” of non-zeres and then assemble the matrix using spdiags (short for sparse diagonals). The vectors are named 1, d and u. They must all have the same length and only the first n—1 terms of 1 are used while the last n— 1 terms of u are used. spdiags places these vectors in the diagonals labelled ~1, 0 and 1 (0 defers to the leading diagonal, negatively numbered diagonals lie below the leading diagonal, ete.) >> Le -(Qemet)'; d= Gem); a = Cast) 21:29! >> B= spdiags((1? @? u’J,-1:1,n,0); >> £ul1(B) Ee et 2. 2 MapshOines 6 Oa ie ead 0 SObesEE: ate 0 1 maw pore: 17 Systems of Linear Equations Mathematical formulations of engineering problems of- tem lead to sets of simultaneous linear equations. Such ar Js the case, for instance, when using the finite element method (FEM). ‘A general system of linear equations can be expressed in terms of a coefficient matrix A, a right-hand-side (column) vector b and an unknown (columa) vector Ax=b or, componentwise, as naz + arate ++ ain ty eaati + anaz2 +++ aantn nytt + On282 + --Onin tn = by When A is nonsingular and square (n x n), meaning that the number of independent equations is equal to the number of unknowns, the system has @ unique so- lution given by x=Atb where A~! isthe inverse of A. Thus, the solution vector x can, in principle, be calculated by taking the inverse of the coefficient matrix A and multiplying it on the right with the rightchand-side vector b, ‘This approach based on the matrix inverse, though for- rally correct, is at best inefficient for practical applica- tions (where the number of equations may be extremely large) but may also give rise to large numerical errors unless appropriate techniques are used. These issues are discussed in most courses and texts on numerical meth ‘ods. Various stable and ficient solution techniques have been developed for solving linear equations and the most appropriate in any situation will depend on the properties of the coefficient matrix A. For instance, ‘on whether or act iti symmetric, or positive definite or itt has a particular structure (sparse or full). Matlab is equipped with many ofthese apecial techniques in its routine library and they are invoked automatically. ‘The standard Matlab routine for solving systems of linear equations is invoked by calling the matrix left- division routine, poxeA\d ‘where “\" is the matrix left-division operator known as “backslash” (see help backslash). Exercise 17-1 Enter the symmetric coefficient matriz and right-hond-side vector b given by 1 ° 1 2-1 0: a=[1 21], 0-12 and solve the system of equations Ax = b using the three alternative methods: 4) x= AD, (the inverse A~* may be computed in Matlab wsing inv(A).) x= AN», 48) x7 = DIA leading to af = b’ / A which makes tse of the ‘slash or “right division” operator n), Overdetermined systems frequently appear in mathe- ‘matical modelling when the parameters of a model are determined by fitting to experimental data. Formally the system looks the same as for square systems but the ‘coefficient matrix is rectangular and so itis not possible ‘to compute an inverse. In these cases 2 solution can be found by requiring that the magnitude of the residual vector r, defined by r=Ax-b, bbe minimized. ‘The simplest and most frequently used ‘measure of the magnitude of r is require the Buclidean length (or norm—see Section 14.1) which corresponds to the sum of squares of the components of the resid- ual. This approach leads to the least squares solution of the overdetermined system. Hence the least squares solution is defined as the vector x that minimizes Tt may be shown that the required solution satisfies the so-called “normal equations” (Ox = d, whore C= ATA and d =A", ‘This system is well-known that the solution of this sys- tem can be overwhelmed by numerical rounding error in practice unless great care is taken in its solution (a large part of the difficulty is inherent in computing the ‘matrix-matrix product ATA). As in the solution of square systems of linear equations, special techniques hhave been developed to address these issues and they have been incorporated into the Matlab routine library. ‘This means that a direct solution to the problem of overdetermined equations is available in Matlab through its lef division operator “\". When the matrix A is not square, the operation x= A\b sutomatically gives the least squares solution to Ax = b. This is illustrated in the next example. 18 Example 17.1 A spring is a mechanical element which, {for the simplest model, is characterized by a linear force- deformation relationship Fok, F being the force loading the spring, k the spring con- stant or stiffness and z the spring deformation. In re- ‘ality the linear force-deformation relationship is only ‘an approzimation, valid for smal forces and deforma- tions. A more accurate relationship, valid for larger deformations, is obtained if non-linear terms are taken into account. Suppose 2 spring model with a quadratic relationship Pokzt kas is to be used and that the model parsmeters, ky and ks, are to be determined from experimental data. Five independent measurements of the force and the corre- sponding spring deformations are measured and these are presented in Table 1. Force FIN] | Deformation = [om] 3 | 0.001 50 | 0.011 500 | 0.013 1000 | 0.30 2000 | 0.75: ‘Table 1: Measured force-deformation date for spring, Using the quadratic forcedeformation relationship to- gether with the experimental data yields an overdoter- ‘mined system of linear equations and the components of the residual are given by sak +2th- Fi = 2h + 23a — Fa = aah 23k — Fe aah tate — Fi = zeh + 23k ~ F n ‘These lead to the matrix and vector definitions a a A nd BR Aq|a xf | ade-| 8% me zy ‘BR oH R. ‘The appropriate Matlab commands give (the compo- nents of x are all multiplied by 1e-2, ie., 10%, in order to change from em to m) >> x= [.001 .011 .13 .3 .75]*t0-2; >> A= Ge (21).72] i 0,0000 9.0000 0.0001 0.0000, 0.0013 0.0000 . 0.0030 0.0000 0.0075 0.0001, >> b = [5 50 500 1000 2000}; 19 and the least squares solution to this system is given by ne ‘oer « ovasse eee Tw, [ 229] 10 ad the gad pig force-deformation relationship that optimally fits ex- perimental data in the least squares sense is Fx 38.6 x 10'2 ~ 16.0 x 10%". ‘The data and solution may be plotted with the follow. ing commands >> plotGs,f,10"), held on >> Km CO! .O1:t)emaxGe); >> plot(K, [X? (f."2)"Tek,?=")_ 4 best fit curve >> elabel(’x(a]’), ylabel FON’) and the results are shown in Figure 5. % plot data points Figure 5: Data for Example 17.1 (circles) and best least squares fit by a quadratic model (solid line) polyfit for data fitting by poly- ste “help polyfit”. It is not applicable in this example because we require that the force ~ de- formation law passes through the origin (so there is no constant term in the quadratic model that we used). 18 Characters, Strings and Text ‘The ability to process text in numerical processing is useful for the input and output of data to the screen or to disk-fles. In order to manage text, a new datatype of “character” is introduced. A plece of text is then imply a string (vector) or array of characters. ‘Example 18.1 The assignment, poet 7a ‘assigns the value A to the 1-by-1 character array t1. ‘The assignment, >> e2 + BODE? assigns the value BCDE to the 1-by-4 character array 2 Strings can be combined by using the operations for array manipulations. The assignment, >> e2 = Cet,e2] assigns a value ABCOE to the 1-by-§ character array ¢3, ‘The assignment, >> th = (t9," are the first 5 ‘characters in the alphabet. 7] sssigns the value "ABODE are the firet 6° ‘characters in the alphabet.’ to the 2-by-27 character array ¢4. It is essential that the number of characters in both rows of the array ¢4 is the same, otherwise an error will result. The three dots... signify that the command is continued on the following line Sometimes it is necessary to convert a character to the corresponding number, or vice versa. These conversions are accomplished by the commands 'str2mun’—which converts a string to the corresponding number, and two functions, "ine2str' and ‘aua2stx’, which convert, re spectively, an integer and a real number to the corre- sponding character string. These commands are useful {or producing titles and strings, such as "The value of pi is 3.1416". This can be generated by the command (Te value of pi is ’,nua2str(pi)] w= 8h = 1; >> [The value of N is ',ine2str(t), o, hw? num2str(i)] The value of Nis 5, h= 0.2 19 Loops ‘There are occasions that we want to repeat a segment of code a number of different times (such occasions are less ‘frequent than other programming languages because of the : notatior), ‘Example 19.1 Draw graphs of sin(nns) on the inter- wel “1S 2S 1 forn=1,2,...,8. We could do this by giving 8 separate plot commands but it is much easier to use a loop. The simplest form would be >> x= -12.05:4; >> for a= 1:8 subplot (4,2,n),, plot (x,ain(nepiex)) ond All the commands between the lines starting “for” and. “end” are repeated with n boing given the value 4 the first time through, 2 the second time, and so forth, until n = 8, The subplot constructs a 4 x 2 array of subwindows and, on the nth time through the loop, a picture is drawn in the nth subwindow. ‘The commands D> x= 1:08:45 >> for m= 1:28 subplot (4,2.n), plot(x,sin(nepiex)) subplot (4,2,n+1),“plot(x,cos(aepiex)) end draw sinnmz and cosnmz for n = 1,3,5,7 alongside each other. We may use any legal variable name as the “loop counter" (a in the above examples) and it can be made to run through all of the values in a given vector (1:8 and 4:2:8 in the examples) We may also use for loops of the type >> for counter = (23 11 19 5.4 6] ond which repeats the code as far as the end with counter=23 the first time, counter=11 the second time, and go forth. Example 19.2 The Fibonnaci sequence starts off with the numbers 0 and 1, then succeeding terms are the sum ofits two immediate predecessors. Mathematically, A =0, fa=1 ond he Test the assertion that the ratio fy-1/fn of two suc- cessive values approaches the golden ratio (VS — 1)/2 = 0.8180 ae fai + fant, >> FCA) = 0; F(2) = >> for 4 = 3:20 FG) © FG-1) + F(i-2); end >> plot(t:19, F(1:19)./F(2:20),%0! ) >> hold on, "xlabel a’) >> plot (1:19, F(4:19)./F(2:20),?-" ) >> legend(/Ratio of verms £(n-1}/t_2") >> plot({0 20], Ceqrt(6)-1)/2e(1, 11," ) ‘The last of these commands produces the dashed hori zontal line, Example 19.8 Produce a list of the values of the sums Sie te Sa tata Sua = Lt bt tet ght he tet he ‘There are a total of 81 sums. The first can be computed using sum(1./(41:20) .“2) (The function sum with a vec- tor argument sums its components. See §22.).) A suit- able piece of Matlab code might be >> $= zeree(100,1); >> $(20) = sum(t./(1:20)."2h; >> for n= 21:100 >> S(a) = S(a-t) + 1/272; >> ond >> elf; phot(S,".", (20 100] , (1, 1}+pi"2/6,'=") >> axis ([20 100 1.5 1.71) >> [ (98:100)? $(98:100)1 ‘98.0000 1.6364 99.0000 1.6365 100.0000 1.6366 where a column vector $ was created to hold the an- swers, The first sum was computed directly using the sun command then each succeeding sum was found by adding 1/n? to ite predecessor. The little table at the end shows the values of the last three sums—it appears that they are approaching limit (the value of the limit is =°/6 = 1.64493...) Exercise 19.1 Repeat Bample 19.9 to include 181 sums (ie, the final sum should include the term 1/2007.) 20 Logicals Matlab represents true and false by means of the in- tegers O and 1. ‘rue = 1, false = 0 fat some point in a calculation a scalar , say, bas been assigned a value, we may make certain logical tests on ie xs= 2 is xequal to 2? x “= 2. is xnot equal to 2? x22 is xgreater than 2” x< 2 isxless than 2? x >= 2. is x greater than or equal to 2? x <2. is xless than or equal to 2? Pay particular attention to the fact that the test for ‘equality involves two equal signs ==. >> x= pi 3.1416 Speen x Pi When x is a vector or a matrix, these tests are per- formed elementwise: “2.0000 3.1416 5.0000 4.0000 ‘© "1.0000 > x0 eo: Oe 1 ee oo Cette at feces ieee Dy swet ary Ee ose: 1 eat ta 9 Waa Hp eieays oo We may combine logical tests, as in -2.0000 3.1416 5.0000 5.0000 3.0000 1.0000 por> sexed Ce) O00 per dlxe 3 Oe ie G4 ‘As one might expect, & represents and and (not so clearly) the vertical bar | means or; also ~ means not as in “> (not equal), ~(>0), ote. Dx>giza3ixe- OP pea i oN One of the uses of logical tests is to “mask out” certain elements of a matrix, pox, Ls x>00 2.0000 3.1416 5.0000 5.0000 3.0000 1.0000 Le Origa: eevee fh >> pos = x.eL a © 3.1816 s.0000 ° ° ° a so the matrix pos contains just those elements of x that Method 1: are non-negative >> x + zeros(1,20); x(t) = pi/4 >> x = 0:0.06:6; y = sin(piex); Y= (>0).4y: G3 ae de 1; >> plot(z.y.?it.z.%s!-? ) >> while d > 0.001 n= met; x(a) = cos(x(a-1)); 4 abs x(a) = x(n-t) ): " end “4 i Columns 1 through 7 a os Ol ae 0.7854 0.7071 0.7602 0.7267 0.7487 0.7326 0.7435 a Columns 8 through 14 0.7361 0.7411 0.7377 0.7400 0.7385 0.7395 0.7388 Columns 15 through 20 O° tos Mb Fgsexo2 mo t + Thee are a number of deficiencies with this program. ‘The vector x stores the results of each iteration but we don’t know ia advance how many there may be. In any event, we are rarely interested in the intermediate i values of x, only the last one. Another problem is that got bile Loeps we may never satisfy the condition d < 0.001, in which ‘There are some occasions when we want to repeat 2 case the program will un forever-—we should place a section of Matlab code until some logical condition is limit on the maximum number of erations sisi, but we cannot tell in advance bow many times Incorporating these improvements leads to te have to go arcund the loop. This we can do with a while. ..end construct. ‘Method 2: Example 20.1 What isthe greatest value of thet can, song = pi/a: a= 1; d= 1 be used in the sur >> wale d > 0.001 & a < 20 Sta a= ntl; xnew = coa(xold); = abs( mou ~ xold ); ‘ond get a value of less than 100? malate icweat >Sent = >> while St (asi)~2 < 100 zee Doig Tote nent; $= 9+ a7 44,0000 0.7388 0.0007 end eae We continue around the loop so long as d > 0.001 and eens 1 < 20. For greater precision we could use the condition 28 > 0.0001, and this gives The lies of code between white and oud will only be tsscwed if th condition $+ Gvi)"2 © 100 run, 22 2 saa¥, xerclse 20.1 Replace 100 the previous exomple ly 18.0000 0.7301 0.0001 40 and work through the lines of code by hand. You should get the answers n= 2 and $= 5. from which we may judge that the root required is = = 0.739 to 3 decimal places. Exercise 20.2 Type the code from Ezample20.1 into 0 The general form of vhile statement is seript-fle named tht LeSum.m (See §19.) while o logical test A more typical example is Commands to be executed when the condition is true Example 20.2 Find the approzimate value of the root of the equation = = cos. (See Bzample 10.1.) We may do this by making a guess 21 = 1/4, sey, then eee sae tee io 20.2 if...then...else...end end This allows us to execute different commands depend- ing on the truth or falsity of some logical tests. To test ang continuing until the difference between two succes- whether or not x* is greater than, or equal to, sive values [rq ~ 2,1] is small enough. Stat, = 2,3,4,.. 22 >> a= pirexp(1); ¢ = exp(pt); > if arr b= sqrt(ar2 - ©72) and ‘0 that b is assigned a value only if a >< There is no output so we deduce that a= nt if arse b= sqrt (ar? - €°2) which ensures that b is always assigned a value and confirming that a ifare b= sqre(ar2 - 72) elseif ave > cra b= ca/ate else b= arc/eva end a 0.2347 Exercise 20.3 Which of the above statements assigned 2 value to»? ‘The general form of the if statement is if logical test 1 Commands to be executed if test 1 is true elseif logical test 2 Commands to be executed if test 2is true but test J is false 21 Function m-files ‘These are « combination of the ideas of script m-files (§7) and mathematical functions. Example 21.1 The area, A, of a triangle with sides of length a, b and c is given by Ax Vals—al(o= B= 9), where #= (0 +b+0)/2. Write a Matlab function that will accept the values a, b and e as inputs and return the value of A os output. ‘The main steps to follow when defining a Matlab func- tién ares 23 1, Decide on a name for the function, making sure that it does not conflict with a name that is al- ready used by Matlab. In this ecample the name of the function is to be area, so its definition will be saved in a file called area. ‘The first line of the file must have the format: function (list of outputs] function. name(list of inputs) For our example, the output () is a function of the three variables (Inputs) a, b and ¢ so the first Tine should read function [A] area(a,b,c) Document the function. That is, describe briefly the purpose of the function and bow it can be used. These lines should be preceded by 1. which signify that they are comment lines that will be Ignored when the function is evaluated, Finally include the code that defines the func- tion. This should be interspersed with sufficient comments to enable another user to understand the processes involved. ‘The complete file might look like: function (AJ = area(a,b,<) % Compute the area of a triangle vhose 4% sides have longch a, b and ¢ % Inputs % —ajbsc: Lengths of sides % Output iy A: area of triangle 2 Usage: % rea = areat2,3,4); U Weivten by dig, Oct 14, 1996. 3 = (arbtc)/2; A= sqre(s*(e-a) «(2-b) wnt end of area ‘The command >> help area will produce the leading comments from the file: Conpute the area of a triangle vhote Sides have length a, b and <. Inputs: asbie: ourput: A: area of triangle Lengths of sides Usage: Area = area(2,3,4); Written by dfg, Oct 14, 1996. To evaluate the area of a triangle with side of length 10, 15, >> Area = area(10, 18,20) Area = 72.6184 where the result of the computation is assigned to the variable area. The variable s used in the definition of tthe function above is @ “local variable": its value is local to the function and cannot be used outside: 797 Undefined function or variable s If we were to be interested in the value of 2 as well as ‘A, then the fist line of the file should be changed to function [A,s] = area(a,b,) where there are two output variables. ‘This function can be called in several different ways: 1. No outputs assigned >> area(10, 15,20) 72.8184 gives only the area (first of the output variables from the fle) assigned to ans; the second output is ignored. 2. One output assigned >> Area = area(t0, 16,20) a 72.6184 again the second output is ignored. 38: Two outputs assigned >> (Area, Ben) = area(10, 15,20) Area = 72.6184 len = 22.5000 Exercise 21-1 In any triangle the sum of the lengths of any wo sides cannot exceed the length of the third side. The function area does not check to see if this condition is fulfilled (try area(1,2,4)). Modify the file 0 that it computes the area only if the sides satisfy this ‘condition 21.1 Examples of functions ‘We revisit the problem of computing tbe Fibonnsci se- quence defined by fr fr= land Ine Initinn 7 We want to construct a function that will return the ‘nth number in the Fibonnaci sequence fn. ‘Input: Integer n + Output: fy Wo shall describe four possible functions and try to as- sess which provides the best solution. 4,5, Method 1: File Fibi.= function f = Fibt (a) 4% Returns the nth aumber in the 4 Fibonacei sequence. Fezeros(1n¢1 FQ) = 4; for i= 3:n¢t FG) = F(i-t) + FG-2); end £2 FQ; This code resembles that given in Example 19.2. We hhave simply enclosed it in a function m-file and given it the appropriate header, ‘Method 2: File Fib2.m ‘The first version was rather wasteful of memory—i ssaved all the entries in the sequence even though we ‘only required the last one for output. The second ver- sioa removes the need to use a vector. function f = Fib2(a) % Returns the nth nunbe 4% Fibonacci sequence. Sf nent £ = 0; in the f1nf2; £2 = end ond Method 3: File: Fib3.2 This version makes use of an idea called “recursive programming”— the function makes calls to itself. function f = Fib3(a) 4% Returns the ath number in the 4% Fibonacci sequence: Af ase £0; eleeif an=2 fet; else f= Fib(a-t) + Fib3(a-2); ead Method 4: File Fib4.m ‘The final version uses matrix powers. The vector y has fn (comes |e function f = Fibé(a) % Returns the ath nusber in the 4% Fibonacci sequence. Aw (04:11; y= Arne(t;01; fy); Assessment: One may think that, on grounds of style, the ard is best (it avoids the use of loops) fol lowed by the second (it avoids the use of a vector). ‘The situation is much different when it cames to speed of ‘execution, When n = 20 the time taken by each of the ‘methods is (in seconds) 24 [Matted —Time_ eval esinad ALES 5 2 oo1sT 3 36.5937 4 0.0078 Ik Is impractical to use Method 3 for any value of much larger than 10 since the time taken by method 3 Almost doubles whenever n is increased by just 1. When n= 150 “Method Time T — 0.0ea0 2 0.0891 3 ze 4 0.0106 Clearly the 4th method is much the fastest 22 Further Built-in Functions 22.1 Rounding Numbers ‘There are a variety of ways of rounding and chopping real numbers to give integers. Use the definitions given in the table in §28 on page 32 in order to understand the output given below: >> x= pirt:3), round(x) “3.1816 0 3.1416 6.2692 9.4240 Sie 0 8 3 os 8 >> fixe) Bate, a eho >> fleor(x) phe 0 5 oes >> ceil(x) mained Tag) >> sign), Bi egos ie ate a 0.1416 0 0.1416 0.2832 0.4248, Do “hep round” for help information. 22.2 The sum Function ‘The “sun” applied to a vector adds up its components (as in sun(1:10)) while, for a matrix, it adds up the components in each column and returns a row vector. ssun(sun(A)) then sums all the entries of A >> k= (4:3; 4:6; 7:91 ie Ae aoe. ae ts 6 Tae >> s = sum(A), 58 = sum(sun()) 1s 18 >> x= pi/te(s:3)? >> A= (sin(x), sin(2ex), sin(3ex)]/sqrt (2) > he (0.5000 0.7071 0.5000 0.7071 0.0000 -0. 7071 0.8000 -0.7071 0.5000 >> si = sun(A.-2), 62 = sun(sum(a.-2)) ste 1.0000 1.0000 1.0000 32° 3.0000 ‘The sums of squares of the entries in each column of & are equal to 1 and the sum of squares of all the entries is equal to 3 >> Aen? ° ° 1.0000 0.0000 0.0000 1.0000 ° ° © 1.0000 0.0000 © 0.0000 1.0000 It appears that the products AA’ and A’A are both equal to the identity: >> kek? ~ e703) 1.0016 + -0.2220 o ° 0 -0.2220 * 0.0555 © 0.0555 -0.2220 >> Alaa = oy0(3) 1.0016 + 0.2220 ° ° 0 -0.2220 0.0865 0 0.0555 | -0.2220 This is confirmed since the differences are at round- off error levels (less than 10~'5), A matrix with this property is called an orthogonal matrix. 22.3 max & min ‘These functions act ina similar way to sun. If x is a ‘vector, then max(x) returns the largest element in x >> x= (1.9 -2.40 2.9), maxx), maxCade(s)) 1.3000 -2.4000 © 2.3000 2.3000 2.4000 >> Ge, j] = maxGe) 2.3000 ae 4 ‘When we ask for two outputs, the first gives us the max- imum entry and the second the index of the maximum element, For a matrix, 4, nax(4) returns a row vector containing ‘the maximum clement from each column. Thus to find ‘he largest element in & we have to use max(max(A)) 22.4 Random Numbers ‘The function rand(m,a) produces an m x n matrix of random numbers, each of which is im the range 0 to 1 rand on its own produces a single random number. >> y= rand, Y= rand(2,3) se 0.9191 Ye 0.6262 0.7446 0.2520 0.6121 0.1875 0.7764 Repeating these commands will lead to different an- Example: Write a junction-fle that will simulate n throws of a pair of dice. ‘This requires random numbers that are integers in the range 1 to 6. Multiplying each random number by 6 will give a real number in the range 0 to 6; rounding these to whole numbers will not be correct since it will then be possible to get 0 as an answer. We need to use Hort + Serand) Recall that floor takes the largest integer that is smaller than a given real number (see Table 2, page 32) File: dic function [4] » dice(a) X simlates "n" throws of a pair of dice % Impuc: —n, the nusber of throvs % Ouepue: an a times 2 matrix, each row % referring to one throv. a 4% Useage: T= dice(3) d= floor(1 + Gerand(a,2)); Wh end of dice >> aica(a) 6 1 i Pen aa >> aun(aice(100))/100 3.8500 3.4300 ‘The last command gives the average value over 100 throws (it should have the value 3.6) 22.5 find for vectors The function “find” returns a list of the positions (in- dices) of the elements of a vector satisfying a given con- dition. For example, D> x = n1:.05:1; >> y = sin(Sepiex) >> ke = find(y > 0.2) is Columns 1 through 12 9 10 11 12 13 22 23 24 2 26 27 36 Columns 13 through 15 37 38 39 >> hold on, plot(x(k) 70) ,’0") >> lm = find( 330.5 & y<0) ie 2 3 OM >> plot (x(a) ,y (em) ,"=) rexp(-x.°2); plot (x,y,?:") 22.6 find for matrices ‘The f1nd-function operates in much the same way for > k= 0-234 405-16; 6801) ae Bhar a a ee scine 6 pee 2 >> k = find (=o) ke 2 9 ‘Thus, we find that A has elements equal to 0 in positions 2and 9, To interpret this result we have to recognie ‘that “find first reshapes & into a column vector—this is equivalent to numbering the elements of by columns 147 10 see wit 36 9 12 >> m = find(A <= 0) 26 >> OLY] = meshgrid(2:.8:4, 1:.8:3); >t xe 2.0000 2.5000 3.0000 3.5000 4.0000 2.0000 2.5000 3.0000 3.5000 4.0000 2.0000 2.5000 3.0000 3.5000 4.0000 2.0000 2.5000 3.0000 3.5000 4.0000 2.0000 2.8060 3.0000 3.5000 4.0000 > ° Ye 4.0000 1.0000 1.0000 1.0000 1.0000 ‘Thus, m gives a list of the locations of the entries in A 5000 1.5000 1.6000 1.8000 1.6000 that are <0 and then A(a) gives us the values of the 2/9900 2.0000 2.0000 2.0000 2.0000 elements selected, ~ 2.6000 2.5000 2.6000 2.8000 2.5000 Soe ay 3.0000 3.0000 3.0000 3.0000 3.0000 a If we think of the ith point along from the left and 5 the jth point up from the bottom of the grid) as corre- i sponding to the (i, j)th entry in a matrix, then (K(4,3), YG, 5)) are the coordinates of the point. We then need to evaluate the function f using x and ¥ in place of 2 and y, respectively. Since we are dealing with A’, the entries are numbered by rows 23 Plotting Surfaces Example 28.1 Plot the surface defined by the function Asurface is defined mathematically by a function f(2,y)— See correrponding to each value of (2,3) we compile the for 2> OM = mosbgrid(a: 2: (zy). >> Z = (K-38). -2- (1-2). 72; >> meench,t,2 >> ehtle('Saddle’), xtabel(*x"),ylabel ry") prey; In order to plot this we have to decide on the ranges fof x and y—suppose 2. > UGA) = meshgrid(-2: .1:2,-2:.2:2); D> £ = Kao sexp(-26Ch.-247.°2)); >> figure (4) £), xlabel (/x?), ylabel(?y?), grid contour (X,Y, £) LCy?), grid, hold on Figure 8: “uesh” and “contour” plots. To locate the maxima of the “£" values on the grid: >> tax = max(nax(£)) fear = 0.0886 >> imax = find (f-=faax) imax = 323 539 >> Pos = OX(kmax), YCcax)] Pos = -0.5000 0.6000 0.5000 0.6000 >> plot(K(anax), Y(emax), 1+?) >> text (k(max) , YGemax),? Maximus’) 24 Timing Matlab allows the timing of sections of code by pro- viding the functions tic and toc. “tic switches on a stopwatch while toc stops it and returns the CPU time 28 Figure 9: contour plot showing maxima. (Central Processor Unit) in seconds. The timings will vary depending on the model of computer being used and its current load. >> tie,for j=1:1000,x = pieR(3) jend, toc elapsed.cine = 0.5110 >> the,for j=1:1000,x-pieR(3) ;end, toc elapsed_tine = 0.5017 >> tie for Jm1:1000,x=R(3) /pi end, toc elepsed_tize - 0.6203, >> tle,for jrt:1000, x=pirR(3) jend, toc elapsedtine = 0.5221 >> the for j=1:1000,x=pi-R(3) jend,toc elepsed_tine = 0.5154 >> tie for J=1:1000, x=pi°R(S) send, toe clapsed.cine = 0.6236 25 On-line Documentation In addition to the on-line help facility, there is a by- pertext browsing system giving details of (most) com- ‘mands and some examples. This is accessed by >> doc which brings up the Netscape document previewer (and allows for “surfing the internet superhighway"—the World Wide Web (WWW). It is connected to a worldwide sys- tem which, given the appropriate addresses, will pro- vide information on almost any topic) Words that are underlined in the browser may be clicked on with LB and lead to either a further subindex or a help page. Scroll down the page shown and click on general which will take you to “General Purpose Commands"; click on lear. This will describe how you can clear a variable's value from memory. ‘Youmay then either click the “Table of Contents” which takes you back to the start, “Index” or the [Back] but- ton at the lower left corner of the window which will take you back to the previous screen. ‘To access other “home pages’, click on [Open] at the bottom of the window and, in the “box” that will open up, type hetp: //ww.maths.dundee.ac.ule Inetp: //uwe maths dundee .ac.uk/softvare/ and select Matlab from the array of choices. 26 Reading and Writing Data Files Direct input of data from keyboard becomes impracti- cal when - the amount of data is large and ‘+ the same data is analysed repeatedly, In these situations input and output is preferably ac- complished via data files, We have already described in Section 9 the use of the commands save and load that, respectively, write and read the values of variables to disk files. When data are written to or read from a file it is cru cially important that a correct data format is used. The data format is the key to interpreting the contents of a file and must be known in order to correctly interpret the data in an input file. There a two types of data files: formatted and unformatted. Formatted data fles uses format strings to define exactly how and in what positions of a record the data is stored. Unformatted. storage, on the other hand, only specifies the number format. ‘The files used in this section are available from the web Ittp: //www.maths dundee.ac.uk/software/tmatlab ‘Those that are unformatted are in a satisfactory form 2. read pairs of numbers from the fle with file iden- tifier £44, one with 3 digits and one with 4 digits, and . 3. close the file with file identifier £14, This produces a column vector « with elements, 100 2286 200 4564 ...500 6432. This vector can be con- verted to § x 2 matrix by the command A= reshape(2,2,5) "3. 26.1 Formatted Files Some computer codes and meaturement instruments Produce results in formatted data files. In order to read these results into Matlab for further analysis the data, format of the files must be known. Formatted files in ASCII format are written to and read from with the commands fprintf and fecant. iprintf(fid, ‘format’, variables) writes vari- ables an a format specified in string ‘format to the file with identifier id = fscant (fid, ‘format’ size) assigns to vari- able a data read from file with identifier fi¢ un- der format ‘format’. Exercise 26.2 Study the available information and help on fscanf and {printf commands. What is the mean- ing of the format string, "%3d\n’ ? Example 26.1 Suppose « sound pressure measurement system produces a record with 512 time ~ pressure read- ings stored on a fle 'seund. dat’ Each rending is listed con a separate line according to a data format specified by the string, "%8.6f 18.6£" A set of commands reading time ~ sound pressure data from 'sound.dae’ is, for the Windows version on Matlab (version 6.1) butStep 1: Assign « namestring to a file identifier. not on Version 5.3 under Unix. Exercise 26.1 Suppose the numeric data is stored in a fle "table. dat’ in the form of a table, as shou below. 100 200 300 400 2256 4554 3653 6798 6432 Step 3: iat? 12); >> a= tecant (tid, "734%4€"); >> felose (fia); respectively. 1. open a file for reading (this is designated by the string 'r’). The variable fd is assigned a unique integer which identifies the file used (a file iden- tiffer). We use this number in all subsequent ref- ferences to the fle. 29 Step 2: >> fiat = fopen(?sound.dat?, x); ‘The string 'r' indicates that data is to be read (not written) from the file. Read the data to a vector named ‘data’ and close the file, >> data = fecant(fidt, °K 16"); >> felese(£idi); Partition the data in separate time and sound pressure vectors, >> t= data(1:2:Length(data)) ; >> press = data(2:2: length (date)); ‘The pressure signal can be plotted in a Lin-Lin diagram, >> plot(t, press); ‘The result is shown in Figure 10. Figure 10: Graph of “sound data” from Exam- ple 26.1 26.2 Unformatted Files Unformatted or binary data files are used when small- sized files are required. In order to interpret an unfor- matted data fle the data precision must be specified. ‘The precision is specified as a string, eg, ‘float32', controlling the number of bits read for each value and the interpretation of those bits as character, integer or ating point values. Precision '‘float32’, for instance, specifies each value in the data to be stored as a floating point number in 32 memory bits Example 26.2 Suppose a system for vibration mea- surement stores measured acceleration values 03 float- ing point numbers using 92 memory bits. The data stored on file 'vib. dat. The following commands ius. trate how the data may be read into Matlab for analysis, ‘Step 1: Assign a fle identifier, £14, to the string specify- lng the file name. >> Hid = fopen(? vib. dat? ,?2b"); ‘Thestring ’rb’ specifies that binary numbers are to be read from the file. Read all data stored on file 'vib. dat’ into a vec- tor vib. >> vib = fread(fid, '#loat32"); >> ftelose (tid); >> size(vib) 131072 ‘The size(vib) command determines the size, i.e, the number of rows and columns of the vi- bration data vector. In order to plot the vibration signal with a correct time scale, the sampling frequency (the umber of instrument readings taken per second) used by the measurement system must be kuowa. In this case it is known to be 24000 Hz so that there is 1 time interval of 1/24000 seconds between two samples, Step 2 Step 8: Create a column vector containing the correct time scale. >> dt = 1/2400; b> t= dee(t:lengthCvib)) 5 Step 4: Plot the vibration signal in a Lin-1in diagram >> plot(t, vib); >> title(/Vibration signal’); >> xlabel (Time, (s]); >> ylabel(’ Acceleration, [a/s~2}'); 27 Graphic User Interfaces The efficiency of programs that are used often and by several different people can be improved by simplifying the input and output data management. The use of Graphic User Interfaces (GUI), which provides facilities ssuch as menus, pushbuttons, sliders etc, allow programs to be used without any knowledge of Matlab. They also provides means for efficient data management. ‘A graphic user interface is a Matlab script file cus- tomized for repeated analysis of a specific type of prob- Jem. There are two ways to design a graphic user inter- face, The simplest methed is to use a tool especially de- signed for the purpose. Matlab provides such a tool and itis invoked by typing ‘guide’ at the Matlab prompt. Maximum flexibility and control over the programming Js, however, obtained by using the basic user interface commands. The following text demonstrates the use of some basic commands. Example 27.1 Suppose a sound pressure spectrum is to be plotied in a graph. There are four alternative plot formats; lin-lin, lin-log, log-lin and log-log. The graphic ‘user interface below reads the pressure data stored on a binary file selected by the user, plots it in a lin-lin for. mat as a function of frequency and lets the user switch between the four plot formats. ‘We use two m-files. The first (specplot.m) is the main driver file which builds the graphics window. It calls the second file (firstplot.n) which allows the user to select among the possible + bin files in the current di- rectory. % File: x 4% OUI for plotting a user 4 in four altarnative plot formats, Lin-lin, 4H Lin-log, log-Lin and log-log. x 4% Author: U Carlsson, 2001-08-22 specplot.= 4% Create figure window for graphe figWindow = figure(’Name’, 'Plot alternatives’); % Create file input selection button ‘fAleinpBen = uicontrol(’Style?, pushbutton’, ‘string’ , File’ , ‘position’, (5,395,40,20] , callback’, ’[£dat,pdat] = firstploe;’); Press 'File’ calle function 'firstplot! 30 elected frequency spectrum 4 Create pushbuttons for switching between four Executing this GUI from the command line 4 different plot formats X= Frequency, [iz]’; Y= ‘Pressure amplitude, (Pal; LinlinBen ~ uicontrol(’style? , pushbutton’, ‘tring’ ,’Lin-Lin’, *position’ , (200,395, 40,20], ’caltback”, *plot(£datpdat) ;x1abel (X) :ylabel (1) 1); LimlogBen = uicontrol(’style’ , pushbutton’, string’, Lin-log’, ‘position’ , (240,395, 40,20], ... veallback”, » semilogy (Edat ,pdat) ;xlabel (X) ;ylabel(¥);"); Loglingta = uicontrol(’style’ ‘pushbutton’, string?’ Log-in’, ‘position’ , (280,395, 40,20), ‘callback’, ?semiloge fdat pdat) ;xLabel( :ylabel(¥) 7): LoglogBtn = uicontrol(’style’ , ‘pushbutton’, string? ,"Log-log?, *position’ , (320,395, 40,20], *ealback’, "oglog(fdat,pdat) jxlabel(H); ylabel (1); " 4% Create exit pushbutton vith red text exitta = uicontrol (’Style’, ‘pushbutton’, ‘string’, /EXIT’ ‘position’ ,(510,395,40, 20) *foregroundcolor’ , {1 0 0], ‘ealiback’, elo U Script file: firetplot.s 4% Brings template for file selection. Reads 4% selected filenaze and path and plots 4% spectrum in a lin-Lin diagran. 4% Output date are frequency and pressure W amplitude voctora: 'féat? and /pdat? 4% Author: U Carlsson, 2001-08-22 function (fdat,pdat] » firstplot 4% call Matlab function ‘uigetfile’ that 4 brings file selction template [¢ilenane,pathnene] = wigetfile(’+.bin’, 'Select binary data-file:’) % Change directory ca (pathname! 4% Open file for reading binary floating 4% point nusbers fia = fopen(filenane, rb’); data = froad(fid, "float32") ; 4% Close tile felose (tid); 4% Partition data vector in frequency and 4 pressure vectors pdat = data(2:2:Length(date)); fdat = data(1:2:length (data); 4% Plot pressure signal in a Lin-Lin diagran plot(fdat pat) 4 Define suitable axis labels xlabel (Frequency, (H2]’); ylabel (Pressure amplitude, (Pa]’); Set up the aris stings.(>> specplo:) brings the following screen. Figure 11: Graph of “vibration data” from Exam- ple 27.1 Example 27.1 illustrates how the ‘callback’ property allows the programmer to define what actions should result when buttons are pushed etc. These actions may consist of single Matlab commands or complicated se- 31 juences of operations defined in various subroutines, Exercise 27.1 Five different sound recordings are stored ‘on binary data files, sound!.bin, sound2. bin, The storage precision is ‘float2’ and the sounds are recorded with sample frequency 12000 Hs. Write a graphic user interface that, opens an interface window and + lets the user select one of the five sounds, ‘+ plots the selected sound pressure signal as func- tion of time in a lin-lin diagram, ‘© lets the user listen to the sound by pushing a ‘SOUND’ button and finally «closes the session by pressing a ‘CLOSE’ button. 28 Command Summary ‘The command >> help will give a list of categories for which help is available (eg. natlab/general covers the topics listed in Table 3, Further information regarding the commands listed in this section may then be obtained by using: >> help topic ty, for example, >> help help 1 soundS. bin abs sqrt sign conj imag real angle sin tan exp Jog, logio cosh sinh ‘tanh acos acosh aeioh atan atan2 atanh ‘round floor fix ceil ‘Absolute value Square root function Signum function Conjugate of a complex number Imaginary part of a complex number Real part of a complex number Phase angle of a complex number ‘Cosine Function Sine function ‘Tangent function Exponential function Natural logarithm Logarithm base 10 Hyperbolic cosine function Hyperbolic sine function Hyperbolic tangent function Inverse cosine Inverse hyperbolic cosine Inverse sine Inverse hyperbolic sine Inverse tan ‘Two-argument. form of inverse tan Inverse hyperbolic tan Round to nearest integer Round towards minus infinity Round towards zero Round towards plus infinity Remainder after division ‘Table 2; Elementary Functions 82 Managing commands and functions: help On-line documentation doc _Load hypertext documentation. what Directory listing of M-, MAT: and MEX-files type List Mefle. lookfor Keyword search through the HELP entries which Locate functions and fies. dene __Run demos “Managing variables and the workspace who List current variables: whos List current variables, long form. load _Retrieve variables from disk save Save workspace variables to disk. clear Clear variables and functions from memory. size Size of matrix. Length Length of vector. disp Display matric or text, Working with files and the operating system, ed Change current working diree- tory. dir Directory listing, delete Delete file. ' Execute operating system com- mand. unix Execute operating system com- mand & return result. diary Save text of MATLAB session. Controlling the command window. cedit Set command line edit/recall fa- cility parameters. cle Clear command window. hone Send cursor home. format Set output format ecto Echo commands inside. script files. nore Control paged output in com- mand window. ‘Quitting from MATLAB. quit Terminate MATLAB. ‘Table 3: General purpose commands. Matrix analyais cond Matrix condition number nora Matrix or vector norm. rcond LINPACK reciprocal. condition estimator. rank Number of linearly independent rows or columns. det Determinant, trace Sum of diagonal elements. null Null space. orth Orthogonalization. ref Reduced row echelon form, Linear equations Vand 7 Linear equation solution, use “help slash” chol Cholesky factorization. lw Factors from Gaussian elimina- tion, iv Matrix inverse. ea Orthogonal- triangular decompo- sition grdelete Delete a column from the QR fac- torization grinsert Insert a column in the QR factor- ization. ans Non-negative least- squares pinv Pseudoinverse. Iscov Least squares in the presence of known covariance. Eigenvalues and singular values eg Eigenvalues and eigenvectors. poly Characteristic polynomial. polyeig Polynomial eigenvalue problem. hess. Hessenberg form. e Generalized eigenvalues rsf2esf Real block diagonal form to com- plex diagonal form. cdf2rat Complex diagonal form to real block diagonal form. schur Schur decomposition. balance Diagonal scaling to improve eigenvalue accuracy. svd Singular value decomposition. Matrix functions. expe Matrix exponential. expni _M- file implementation of expm. expn2 Matrix exponential via Taylor se- expn3 Matrix exponential via eigenval- ues and eigenvectors. Joga Matrix logarithm. sqrtn Matrix square root. funm Evaluate general matrix function. ‘Table 4: Matrix functions—numerical linear alge- bra, 33 Graphics & plotting: figure Create Figure (graph window), elt lear current figure, close Close figure. subplot Create axes in tiled positions axis Control axis scaling and appear- hold Hold current graph. figure Create figure window. text Create text. print Save graph to file. plot Linear plot. Loglog —_Log-log scale plot. semilogx Semi-log scale plot. semilogy Semi-log scale plot. ‘Specialized X-Y graphs. polar Polar coordinate plot. bar Bar graph. stem Discrete sequence or "stem” plot. stairs Stairstep plot. errorbar Error bar plot. hist Histogram plot rose Angle histogram plot. compass Compass plot. feather Feather plot. fploe Plot function. comet Comet-like trajectory. Graph annotation title raph title. xlabel ‘X-axis label. ylabel Y-axis label. text ‘Text annotation gtext Mouse placement of text. grid Grid lines. contour Contour plot. nosh 3-D mesh surface. surt 3-D shaded surface. waterfall Waterfall plot. view &D graph viewpoint specifica- tion, zlabel Z-axis label for 3-D plots. gtext Mouse placement of text grid Grid lines. ‘Table 5: Graphics & plot commands. ‘ 18 112 pia +5, 16 23 abs, 32 accelerators keyboard, 9 and, 21 angle, 32 ans, 3 array, 13 axes, 9, 13 axis, 9 fauto, 9 normal, 9 square, 9 browser, 28 ceil, 92 lf, 8 close, 8 colon notation, 5, 16 column vectors, 5 comment (1), 10, 23, complex. conjugate transpose, 5 sumbers, 5 complex numbers, 3 ‘components of a vector, 4 con), 32 contour, 27 copying output, 9 0s, 32 CPU, 28 cursor keys, 9 dono, 3 aiag, 15 ary, 6 dice, 26 divide dot, 12 documentation, 28, dot divide ./, 12 power .*, 12 product .*, 11, 16 echo, 10 elementary functions, 4 eye, 14 false, 21 Fibonnaci, 20, 24 figure, 8 file function, 23 script, 10 find, 26 fix, 32 floor, 32 floor, 26 for loop, 20 format, 3 ong, 12, funetion m-files, 23, functions elementary, 4 trigonometric, 4 get, 8 graphs, see plotting grid, 7, 13,27 GUT, 30 hhard copy, 7 help, 2, 23, hold, 7, 13, home page, 28 Af statement, 22 imag, 32 keyboard accelerators, 9 labels for plots, 6 Legend, 7 length of a vector, 4, 5, 10 line styles, 7 logical conditions, 21 loops, 20 while, 22 mfiles, 10, 23, matrix, 13 building, 15 diagonal, 14 identity, 14 sparse, 17 special, 14 spy, 15 square, 14 ‘symmetric, 14 eros, 14 matrix products, 17 matrix-vector products, 16 anax, 25, 27 nesh, 27 neshgrid, 27 ia, 25, 27 nore, 2 multi-plots, 7 Netscape, 28 norm of a vector, 11 not, 21, 23 pumbers, 3 - complex, 3 format, 3 random, 26 rounding, 25 ones, 14 or, 21 plot, 20 plotting, 6, 12, 27 labels, 6 line styles, 7 priating, 7 surfaces, 27 title, 6 power dot, 12 printing plots, 7 priorities ‘im arithmetic, 3 product, dot, 11, 16 scalar, 16, 17 quit, 2 rand, 26. random aumbers, 26 real, 32 rem, 32 round, 32 rounding error, 4 rounding numbers, 25, earei6 scalar product, 10, 16, 17 seript fies, 10 semi-colon, 4, 13 set, 9 shipes, 7 sin, 32 sin, 32 size, 19 ore, 5 sparse 17 spdiags, 17 spy 15 sar, 32 35 strings, 6 subplot, 8, 20 subscripts, 8 ‘sun, 21, 25 superscripts, 8 surfing the internet highway, 28 timing, 28 ‘title for plots, 6 toc, 28 transposing, 5 tridjagonal, 17 trigonometric functions, 4 true, 21 ‘eype (list contents of m-file), 10 wavisble names, 3 vector components, 4 vectors ‘column, 5 rom, 4 what, 10 while loops, 22, whos, 6 WwW, 28 xlabel, 6, 27 xter, 2 ylabel, 6 zeros, 14 2008, 8

You might also like