11.07.2015 Views

MatlabNotes

MatlabNotes

MatlabNotes

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

An Introduction to MatlabVersion 3.0David F. Grithsformerly ofDepartment of MathematicsThe University of DundeeDundee DD1 4HNScotland, UKWith additional material by Ulf CarlssonDepartment of Vehicle EngineeringKTH, Stockholm, SwedenThanks to Dr Anil Bharath, Imperial College,for his contributions to this revised version.Copyright c 1996 by David F. Gri ths. Amended October, 1997, August 2001, September 2005,October 2012.This introduction may be distributed provided that it is not be altered in any way and that itssource is properly and completely specified.


Contents1 MATLAB 22 Starting Up 23 Matlab as a Calculator 34 Numbers & Formats 35 Variables 35.1 Variable Names . . . . . . . . . . 36 Suppressing output 47 Built–In Functions 47.1 Trigonometric Functions . . . . . 47.2 Other Elementary Functions . . . 48 Vectors 58.1 The Colon Notation . . . . . . . 58.2 Extracting Parts of Vectors . . . 68.3 Column Vectors . . . . . . . . . . 68.4 Transposing . . . . . . . . . . . . 69 Keeping a record 710 Script Files 711 Keyboard Accelerators 812 Arithmetic with Vectors 812.1 Inner Product (*) . . . . . . . . . 812.2 Elementwise Product (.*) . . . . 912.3 Elementwise Division (./) . . . . 1012.4 Elementwise Powers (.^) . . . . . 1113 Plotting Functions 1213.1 Plotting—Titles & Labels . . . . 1213.2 Grids . . . . . . . . . . . . . . . . 1213.3 Line Styles & Colours . . . . . . 1213.4 Multi–plots . . . . . . . . . . . . 1313.5 Hold . . . . . . . . . . . . . . . . 1313.6 Hard Copy . . . . . . . . . . . . 1313.7 Subplot . . . . . . . . . . . . . . 1413.8 Zooming . . . . . . . . . . . . . . 1413.9 Figure Properties . . . . . . . . . 1413.10Formatted text on Plots . . . . . 1513.11Controlling Axes . . . . . . . . . 1615 Two–Dimensional Arrays 1715.1 Size of a matrix . . . . . . . . . . 1815.2 Transpose of a matrix . . . . . . 1815.3 Special Matrices . . . . . . . . . 1815.4 The Identity Matrix . . . . . . . 1915.5 Diagonal Matrices . . . . . . . . 1915.6 Building Matrices . . . . . . . . . 2015.7 Tabulating Functions . . . . . . . 2015.8 Extracting Parts of Matrices . . 2015.9 Elementwise Products (.*) . . . 2115.10Matrix–vector products . . . . . 2115.11Matrix–Matrix Products . . . . . 2215.12Sparse Matrices . . . . . . . . . . 2316 Systems of Linear Equations 2316.1 Overdetermined systems . . . . . 2417 Characters, Strings and Text 2618 Loops 2719 Timing 2820 Logicals 2820.1 While Loops . . . . . . . . . . . . 2920.2 if...then...else...end . . . . 3021 Further Built–in Functions 3121.1 Rounding Numbers . . . . . . . . 3121.2 The sum Function . . . . . . . . . 3121.3 max & min . . . . . . . . . . . . . 3221.4 Random Numbers . . . . . . . . 3221.5 find for vectors . . . . . . . . . . 3221.6 find for matrices . . . . . . . . . 3222 Function m–files 3323 Plotting Surfaces 3624 Reading/Writing Data Files 3824.1 Formatted Files . . . . . . . . . . 3924.2 Unformatted Files . . . . . . . . 3925 Graphic User Interfaces 4026 Command Summary 4114 Elementwise Examples 171


1 MATLAB• Matlab is an interactive system for doingnumerical computations.• A numerical analyst called Cleve Molerwrote the first version of Matlab in the1970s. It has since evolved into a successfulcommercial software package.• Matlab relieves you of a lot of the mundanetasks associated with solving problemsnumerically. This allows you to spendmore time thinking, and encourages youto experiment.• Matlab makes use of highly respected algorithmsand hence you can be confidentabout your results.• Powerful operations can be performed usingjust one or two commands.• You can build up your own set of functionsfor a particular application.• Excellent graphics facilities are available,and the pictures can be inserted into L A TEXand Word documents.These notes provide only a brief glimpse of thepower and flexibility of the Matlab system. Fora more comprehensive view we recommend thebookMatlab Guide 2nd ed.D.J. Higham & N.J. HighamSIAM Philadelphia, 2005, ISBN:0-89871-578-4.2 Starting UpMatlab can be used in a number of di↵erentways or modes; as an advanced calculator in thecalculator mode, in a high level programminglanguage mode and as a subroutine called froma C-program. More information on the first twoof these modes is provided by these notes.When used in calculator mode all Matlab commandsare entered to the command line fromthe keyboard at the “command line prompt”indicated with ’>>’.Type quit at any time to exit from Matlab.Extensive documentation is available, either viathe command line by using the ’help topic’command (see below) or via the internet. Werecommend starting with the commanddemo(a link may also be provided on the top lineof the command window). This brings up aseparate window which gives access to a shortvideo entitled “Getting Started” that describesthe purpose of the various panes in the mainMatlab window.Help is available from the command line prompt.Type help help for “help” (which gives a briefsynopsis of the help system), help for a list oftopics. The first few lines of this readHELP topics: --MatlabCode/matlab - (No table of contents file)matlab/general - General purpose commands.matlab/ops - Operators and special ...matlab/lang - Programming language ...matlab/elmat - Elementary matrices and ...matlab/randfun - Random matrices and ...matlab/elfun - Elementary math functions.matlab/specfun - Specialized math functions.(truncated lines are shown with . . . ). Then toobtain help on “Elementary math functions”,for instance, type>> help elfunClicking on a key word, for example sin willprovide further information together with a linkto doc sin which provides the most extensivedocumentation on a keyword along with examplesof its use.Another useful facility is to use thelookfor keywordcommand, which searches the help files for thekeyword. See Exercise 15.1 (page 22) for anexample of its use.2


3 Matlab as a CalculatorThe basic arithmetic operators are + - * / ^and these are used in conjunction with brackets:( ). The symbol ^ is used to get exponents(powers): 2^4=16.You should type in the commands shown at theprompt: >>.>> 2 + 3/4*5ans =5.7500>>Is this calculation 2 + 3/(4*5) or 2 + (3/4)*5?Matlab works according to the priorities:1. quantities in brackets,2. powers 2 + 3^2 )2 + 9 = 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)*5by priority 3.4 Numbers & FormatsMatlab recognizes several di↵erent kinds of numbersType ExamplesInteger 1362, 217897Real 1.234, 10.76Complex 3.21 4.3i (i = p 1)Inf Infinity (result of dividing by 0)NaN Not aNumber, 0/0The “e” notation is used for very large or verysmall numbers:-1.3412e+03 = 1.3412 ⇥ 10 3 = 1341.2-1.3412e-01 = 1.3412 ⇥ 10 1 = 0.13412All computations in MATLAB are done in doubleprecision, which means about 15 significantfigures. How Matlab prints numbers is controlledby the “format” command. Type helpformat for full list.Should you wish to switch back to the defaultformat then format will su ce.Command>>format short>>format short e>>format long e>>format short>>format bankThe commandformat compactExample of Output31.4162(4–decimal places)3.1416e+013.141592653589793e+0131.4162(4–decimal places)31.42(2–decimal places)is also useful in that it suppresses blank lines inthe output thus allowing more information tobe displayed.5 Variables>> 3-2^4ans =-13>> ans*5ans =-65The result of the first calculation is labelled“ans” by Matlab and is used in the second calculation,where its value is changed.We can use our own names to store numbers:>> x = 3-2^4x =-13>> y = x*5y =-65so that x has the value 13 and y = 65. Thesecan be used in subsequent calculations. Theseare examples of assignment statements: valuesare assigned to variables. Each variablemust be assigned a value before it may be usedon the right of an assignment statement.5.1 Variable NamesLegal names consist of any combination of lettersand digits, starting with a letter. Theseare allowable:NetCost, Left2Pay, x3, X3, z25c53


These are not allowable:Net-Cost, 2pay, %x, @signUse names that reflect the values they represent.Special names: you should avoid usingeps (which has the value 2.2204e-16= 2 54which is the largest number such that 1 + epsis indistinguishable from 1) andpi = 3.14159... = ⇡.If you wish to do arithmetic with complex numbers,bothi and j have the value p 1 unlessyou change them>> i,j, i=3ans = 0 + 1.0000ians = 0 + 1.0000ii = 3See Section 8.4 for more on complex numbers.6 Suppressing outputOne often does not want to see the result of intermediatecalculations—terminate the assignmentstatement or expression with semi–colon>> x=-13; y = 5*x, z = x^2+yy =-65z =104>>the value of x is hidden. Note that we canplace several statements on one line, separatedby commas or semi–colons.Exercise 6.1 In each case find the value of theexpression in Matlab and explain precisely theorder in which the calculation was performed.i) -2^3+9 ii) 2/3*3iii) 3*2/3 iv) 3*4-5^2*2-3v) (2/3^2*5)*(3-4^3)^2 vi) 3*(3*4-2*5^2-3)7 Built–In Functions7.1 Trigonometric FunctionsThose known to Matlab aresin, cos, tanand their arguments should be in radians.e.g. to work out the coordinates of a point ona circle of radius 5 centred at the origin andhaving an elevation 30 o = ⇡/6 radians:>> x = 5*cos(pi/6), y = 5*sin(pi/6)x =4.3301y =2.5000To work in degrees, use sind, cosd and tand.The inverse trig functions are called asin, acos,atan (as opposed to the usual arcsin or sin 1etc.). The result is in radians.>> acos(x/5), asin(y/5)ans = 0.5236ans = 0.5236>> pi/6ans = 0.52367.2 Other Elementary FunctionsThese include sqrt, exp, log, log10>> x = 9;>> sqrt(x),exp(x),log(sqrt(x)),log10(x^2+6)ans =3ans =8.1031e+03ans =1.0986ans =1.9395exp(x) denotes the exponential function exp(x) =e x and the inverse function is log:>> format long e, exp(log(9)), log(exp(9))ans = 9.000000000000002e+00ans = 9>> format shortand we see a tiny rounding error in the firstcalculation. log10 gives logs to the base 10.A more complete list of elementary functions isgiven in Table 2 on page 42.4


8.2 Extracting Parts of Vectors>> r5 = [1:2:6, -1:-2:-7]r5 =1 3 5 -1 -3 -5 -7To get the 3rd to 6th entries:>> r5(3:6)ans =5 -1 -3 -5To get alternate entries:>> r5(1:2:7)ans =1 5 -3 -7What does r5(6:-2:1) give?See help colon for a fuller description.8.3 Column VectorsThese have similar constructs to row vectorsexcept that entries are separated by ; or “newlines”>> c = [ 1; 3; sqrt(5)]c =1.00003.00002.2361>> c2 = [345]c2 =345>> c3 = 2*c - 3*c2c3 =-7.0000-6.0000-10.5279so column vectors may be added or subtractedprovided that they have the same length.The length of a vector (number of elements)can be determined by>> length(c)ans = 3>> length(r5)ans = 7and does not distinguish between row and columnvectors (compare with size described in§15.1). The size might be needed to determinethe last element in a vector but this canbe found by using the reserved word end:>> c2(end), c2(end-1:end)ans =4ans =4 58.4 TransposingWe can convert a row vector into a column vector(and vice versa) by a process called transposingwhich is denoted by ’.>> w, w’, [1 2 3], [1 2 3]’w =1 -2 3ans =1-23ans =1.00003.00002.2361ans =1.0000 3.0000 2.2361>> t = w + 2*[1 2 3]’t =3.0000 4.0000 7.4721>> T = 5*w’-2*[1 2 3]T =3.0000-16.000010.5279If x is a complex vector, thenx’ gives the complexconjugate transpose of x:>> x = [1+3i, 2-2i]ans =1.0000 + 3.0000i 2.0000 - 2.0000i>> x’ans =1.0000 - 3.0000i2.0000 + 2.0000i6


Note that the components of x were definedwithout a * operator; this means of definingcomplex numbers works even when the variablei already has a numeric value. To obtain theplain transpose of a complex number use .’ asin>> x.’ans =1.0000 + 3.0000i2.0000 - 2.0000iOne must be aware at all times, as the nextexample shows:and the computation can be resumed where youleft o↵. We do not advocate this procedure exceptis special circumstances, but suggest makinguse of script files (see Section 10).A list of variables used in the current sessionmay be seen with>> whosThey can also be seen in the “Workspace” paneof the main window. See help whos and helpsave.>> whos>> i=3; [1+2i, 3-i, 3-1i]ans =1.0000 + 2.0000i 0 3.0000 - 1.0000iin which only the 2nd element has been influencedby the value of the variable i.9 Keeping a recordIssuing the command>> diary mysessionwill cause all subsequent text that appears onthe screen to be saved to the file mysessionlocated in the directory in which Matlab wasinvoked. You may use any legal filename exceptthe names on and off. The record may beterminated by>> diary offThe file mysession may be edited with yourfavourite editor (the Matlab editor, emacs, oreven Word) to remove any mistakes.If you wish to quit Matlab midway through acalculation so as to continue at a later stage:>> save thissessionwill save the current values of all variables to afile called thissession.mat. This file cannotbe edited. When you next startup Matlab,type>> load thissessionName Size Elements Bytes Density Complexans 1 by 1 1 8 Full Nov 1 by 3 3 24 Full Nov1 1 by 2 2 16 Full Nov2 1 by 2 2 16 Full NoGrand total 16 elements using 128 bytes10 Script FilesScript files are ordinary ASCII (text) files thatcontain Matlab commands. It is essential thatsuch files have names having an extension .m(e.g., myfile.m) and, for this reason, they arecommonly known as m-files. The commands inthis file may then be executed using>> myfileNote: the command does not include the filename extension .m.Script files are created with the built-in editor(it is possible to change to your favourite editorin the Preferences window). Any text thatfollows % on a line is ignored. This enables descriptivecomments to be included. It is possible,via a mouse menu, to highlight commandsthat appear in the “Command History” paneto create a script file. “Cut and Paste” canbe used to copy individual commands from the“Command History” pane into a script file.Exercise 10.1 1. Type in the commands from§8.4 into a file called exsub.m. Its contentsmight look like:7


% My first script file: exsub.mw, w’, [1 2 3], [1 2 3]’t = w + 2*[1 2 3]’% Use w to compute TT = 5*w’-2*[1 2 3]2. Check in the “Current Folder” pane ofthe Matlab window (or use the commandwhat, which lists the m-files in the currentdirectory) to see that the file is inthe correct area.3. Use the command type exsub to see thecontents of the file.4. Execute the file with the command exsub.It is only the output from the commands (andnot the commands themselves) that are displayedon the screen. To see the commands inthe command window prior to their execution:>> echo onand echo off will turn echoing o↵. Comparethe e↵ect of>> echo on, exsub, echo offwith the results obtained earlier.See §22 for the related topic of function files.11 Keyboard AcceleratorsOne can recall previous Matlab commands inthe Command Window by using the " and #cursor keys. Repeatedly pressing " will reviewthe previous commands (most recent first) and,if you want to re-execute the command, simplypress the return key.To recall the most recent command startingwith p, say,typep at the prompt followed by". Similarly, typing pr followed by " will recallthe most recent command starting with pr.Once a command has been recalled, it may beedited (changed). You can use and ! tomove backwards and forwards through the line,characters may be inserted by typing at the currentcursor position or deleted using the Delkey. This is most commonly used when longcommand lines have been mistyped or whenyou want to re–execute a command that is verysimilar to one used previously.The following emacs–like commands may alsobe used:cntrl acntrl ecntrl fcntrl bcntrl dmove to start of linemove to end of linemove forwards one charactermove backwards one characterdelete character under the cursorOnce the command is in the required form,press return.Exercise 11.1 Type in the commands>> x = -1:0.1:1;>> plot(x,sin(pi*x),’w-’)>> hold on>> plot(x,cos(pi*x),’r-’)Now use the cursor keys with suitable editing toexecute:>> x = -1:0.05:1;>> plot(x,sin(2*pi*x),’w-’)>> plot(x,cos(2*pi*x),’r-.’), hold off12 Arithmetic with Vectors12.1 Inner Product (*)We shall describe two ways in which a meaningmay be attributed to the product of two vectors.In both cases the vectors concerned musthave the same length.The first product is the standard inner product.Suppose that u and v are two vectors of lengthn, u being a row vector and v a column vector:u =[u 1 ,u 2 ,...,u n ] , v = 6423v 1v 27. 5 .v nThe inner product is defined by multiplying thecorresponding elements together and adding theresults to give a single number (inner).u ⇤ v =nXu i v i .i=18


For example, if u = [10, 11, 12], v =then n = 3 and24 202122u⇤v = 10⇥20+( 11)⇥( 21)+12⇥( 22) = 167.We can perform this product in Matlab bynorms: help norm.>> u = [ 10, -11, 12], v = [20; -21; -22]>> prod = u*v % row times column vectorSuppose we also define a row vector w and acolumn vector z by>> w = [2, 1, 3], z = [7; 6; 5]w =2 1 3z =765and we wish to form the inner products of uwith w and v with z.>> u*w??? Error using ==> *Inner matrix dimensions must agree.an error results because w is not a column vector.Recall from page 6 that transposing (with ’)turns column vectors into row vectors and viceversa. So, to form the inner product of two rowvectors or two column vectors,>> u*w’ % u & w are row vectorsans =45>> u*u’ % u is a row vectorans =365>> v’*z % v & z are column vectorsans =-96The Euclidean length of a vector is an exampleof the norm of a vector; it is denoted by thesymbol kuk and defined byvuXkuk = t n |u i | 2 ,i=1where n is its dimension. This can be computedin Matlab in one of two ways:35>> [ sqrt(u*u’), norm(u)]ans =19.1050 19.1050where norm is a built–in Matlab function thataccepts a vector as input and delivers a scalaras output. It can also be used to compute otherExercise 12.1 The angle, ✓, between two columnvectors x and y is defined bycos ✓ =x0 ykxk kyk .Use this formula to determine the cosine of theangle betweenx =[1, 2, 3] 0 and y =[3, 2, 1] 0 .Hence show that the angle is 44.4153degrees.[Hint: see cosd and acosd.]12.2 Elementwise Product (.*)The second way of forming the product of twovectors of the same length is known as the Hadamardproduct. It is rarely used in the course of normalmathematical calculations but is an invaluableMatlab feature. It involves vectors of thesame type. If u and v are two vectors of thesame type (both row vectors or both columnvectors), the mathematical definition of this product,which we shall call the Hadamard product,isthevector having the componentsu · ⇤v =[u 1 v 1 ,u 2 v 2 ,...,u n v n ].The result is a vector of the same length andtype as u and v. Thus,wesimplymultiplythecorresponding elements of two vectors. Summingthe entries in the resulting vector wouldgive their inner product.For example, if u = [10, 11, 12], and w =[2, 1, 3] then n = 3 andu. ⇤ w = [10 ⇥ 2, ( 11) ⇥ (1), 12 ⇥ (3)]= [20, 11, 36]In Matlab, the product is computed with theoperator .* and, using the vectors u, v, w, zdefined on page 9,9


u.*wans =20 -11 36>> u.*v’ans =200 231 -264>> v.*zans =140-126-110Perhaps the most common use of the Hadamardproduct is in the evaluation of mathematicalexpressions so that they may be plotted.Example 12.1 Tabulate the functiony = x sin ⇡x for x =0, 0.25,...,1.The display is clearer with column vectors sowe first define a vector of x-values: (see Transposing:§8.4)>> x = (0:0.25:1)’;To evaluate y we have to multiply each elementof the vector x by the corresponding element ofthe vector sin ⇡x:x ⇥ sin ⇡x = x sin ⇡x0 ⇥ 0= 00.2500 ⇥ 0.7071 = 0.17680.5000 ⇥ 1.0000 = 0.50000.7500 ⇥ 0.7071 = 0.53031.0000 ⇥ 0.0000 = 0.0000To carry this out in Matlab:>> y = x.*sin(pi*x)y =00.17680.50000.53030.0000Note: a) the use of pi, b)x and sin(pi*x)are both column vectors (the sin function isapplied to each element of the vector). Thus,the Hadamard product of these is also a columnvector.Exercise 12.2 Enter the vectorsU =[6, 2, 4], V =[3, 2, 3, 0],2 3 2 333W = 6 474 2 5 , Z = 6 274 2 567into Matlab. Which of the productsU*V, V*W, U*V’, V*W’, W*Z’, U.*VU’*V, V’*W, W’*Z, U.*W, W.*Z, V.*Wis legal? State whether the legal products arerow or column vectors and give the values ofthe legal results.12.3 Elementwise Division (./)In Matlab, the operator ./ is defined to giveelement by element division of one vector byanother—it is therefore only defined for vectorsof the same size and type.>> a = 1:5, b = 6:10, a./ba =1 2 3 4 5b =6 7 8 9 10ans =0.1667 0.2857 0.3750 0.4444 0.5000If we change to format rat (short for rational)>> format rat>> (1:5)./(6:10)ans =1/6 2/7 3/8 4/9 1/2>> format compactthe output is displayed in fractions. Note that>> a./aans =1 1 1 1 1>> c = -2:2, a./cc =-2 -1 0 1 2Warning: Divide by zeroans =-0.5000 -2.0000 Inf 4.0000 2.5000The previous calculation required division by0—notice the Inf, denoting infinity, in the answer.10


a.*b -24, ans./cans =-18 -10 0 12 26Warning: Divide by zeroans =9 10 NaN 12 13Here we are warned about 0/0—giving a NaN(Not aNumber).Example 12.2 Estimate the limitsin ⇡xlimx!0 x .The idea is to observe the behaviour of the ratiosin ⇡xxfor a sequence of values of x that approachzero. Suppose that we choose the sequencedefined by the column vector>> x = [0.1; 0.01; 0.001; 0.0001]then>> sin(pi*x)./xans =3.09023.14113.14163.1416which suggests that the values approach ⇡. Toget a better impression, we subtract the value of⇡ from each entry in the output and, to displaymore decimal places, we change the format>> format long>> ans -pians =-0.05142270984032-0.00051674577696-0.00000516771023-0.00000005167713Can you explain the pattern revealed in thesenumbers?We also need to use ./ to compute a scalardivided by a vector:>> 1/x??? Error using ==> /Matrix dimensions must agree.>> 1./xans =10 100 1000 10000so 1./x works, but 1/x does not.12.4 Elementwise Powers (.^)The square of each element of a vector could becomputed with the command u.*u. However,a neater way is to use the .^ operator:>> u = [10, 11, 12]; u.^2ans =100 121 144>> u.*uans =100 121 144>> ans.^(1/2)ans =10 11 12>> u.^4ans =10000 14641 20736>> v.^2ans =400441484>> u.*w.^(-2)ans =2.5000 -11.0000 1.3333Recall that powers (.^ in this case) are donefirst, before any other arithmetic operation. Fractionaland decimal powers are allowed.When the base is a scalar and the power is avector we get>> n = 0:4n =0 1 2 3 4>> 2.^nans =1 2 4 8 16and, when both are vectors of the same dimension,>> x = 1:3:15x =1 4 7 10 13>> x.^nans =1 4 49 1000 2856111


13 Plotting FunctionsIn order to plot the graph of a function, y =sin 3⇡x for 0 apple x apple 1, say, it is sampled atasu ciently large number of points and thepoints (x, y) joined by straight lines. Supposewe take N + 1 sampling points equally spaceda distance h apart:>> N = 10; h = 1/N; x = 0:h:1;defines the set of points x =0,h,2h, . . . , 1 h, 1with h = 0.1. Alternately, we may use thecommand linspace: The general form of thecommand is linspace (a,b,n) which generatesn + 1 equispaced points between a and b,inclusive. So, in this case we would use thecommand>> x = linspace (0,1,11);The corresponding y values are computed by>> y = sin(3*pi*x);and finally, we can plot the points with>> plot(x,y)The result is shown in Fig. 1 below, where it isclear that the value of N is too small.Fig. 2: Graph of y =sin3⇡x for 0 apple x apple 1using h =0.01.13.1 Plotting—Titles & LabelsTo put a title and label the axes, we use>> title(’Graph of y = sin(3pi x)’)>> xlabel(’x axis’)>> ylabel(’y-axis’)The strings enclosed in single quotes, can beanything of our choosing. Some simple L A TEXcommands are available for formatting mathematicalexpressions and Greek characters—seeSection 13.10.See also ezplot the “Easy to use function plotter”.13.2 GridsA dotted grid may be added by>> grid onand is removed with grid off.Fig. 1: Graph of y =sin3⇡x for 0 apple x apple 1using h =0.1.On changing the value of N to 100:>> N = 100; h = 1/N; x = 0:h:1;>> y = sin(3*pi*x); plot(x,y)we get the picture shown in Fig. 2.13.3 Line Styles & ColoursThe default is to plot solid lines. A solid redline is produced by>> plot(x,y,’r--x’)The third argument is a string comprising charactersthat specify the colour (red), the linestyle (dashed) and the symbol (x) tobedrawnat each data point. The order in which theyappear is unimportant and any, or all, may beomitted. The options for colours, styles andsymbols include:12


Colours Line Styles/symbolsy yellow . pointm magenta o circlec cyan x x-markr red + plusg green - solidb blue * starw white : dottedk black -. dashdot-- dashedThe number of available plot symbols is widerthan shown in this table. Use help plot toobtain a full list. See also help shapes.The command clf clears the current figure whileclose(1) will close the graphics window labelled“Figure 1”. To open a new figure windowtype figure or, to get a window labelled“Figure 9”, for instance, type figure (9). If“Figure 9” already exists, this command willbring this window to the foreground and thenext plotting commands will be drawn on it.13.4 Multi–plotsSeveral graphs may be drawn on the same figureas in>> plot(x,y,’k-’,x,cos(3*pi*x),’g--’)A descriptive legend may be included with>> legend(’Sin curve’,’Cos curve’)which will give a list of line–styles, as they appearin the plot command, followed by the briefdescription provided in the command.For further information do help plot etc.The result of the commands>> plot(x,y,’k-’,x,cos(3*pi*x),’g--’)>> legend(’Sin curve’,’Cos curve’)>> title(’Multi-plot’)>> xlabel(’x axis’), ylabel(’y axis’)>> gridis shown in Fig. 3. The legend may be movedeither manually by dragging it with the mouseor as described in help legend.Fig. 3: Graph of y =sin3⇡x and y = cos 3⇡xfor 0 apple x apple 1 using h =0.01.13.5 HoldA call to plot clears the graphics window beforeplotting the current graph. This is not convenientif we wish to add further graphics to thefigure at some later stage. To stop the windowbeing cleared:>> plot(x,y,’r-’), hold on>> plot(x,y,’gx’), hold off“hold on” holds the current picture; “hold off”releases it (but does not clear the window, whichcan be done with clf). “hold” on its own togglesthe hold state.13.6 Hard CopyTo obtain a printed copy select Print from theFile menu on the Figure toolbar.Alternatively one can save a figure to a file forlater printing (or editing). A number of formatsis available (use help print to obtain alist). To save the current figure in “EncapsulatedColor PostScript” format, issue the Matlabcommandprint -depsc fig1which will save a copy of the image in a filecalled fig1.eps.print -f4 -djpeg90 figbwill save figure 4 as a jpeg file figb.jpg at aquality level of 90. It should be borne in mindthat neither command (despite its name) sendsthe file to a printer.13


13.7 SubplotThe graphics window may be split into an m⇥narray of smaller windows into each of which wemay plot one or more graphs. The windowsare counted 1 to mn row–wise, starting fromthe top left. Both hold and grid work on thecurrent subplot.>> subplot(221), plot(x,y)>> xlabel(’x’),ylabel(’sin 3 pi x’)>> subplot(222), plot(x,cos(3*pi*x))>> xlabel(’x’),ylabel(’cos 3 pi x’)>> subplot(223), plot(x,sin(6*pi*x))>> xlabel(’x’),ylabel(’sin 6 pi x’)>> subplot(224), plot(x,cos(6*pi*x))>> xlabel(’x’),ylabel(’cos 6 pi x’)subplot(221) (or subplot(2,2,1)) specifiesthat the window should be split into a 2 ⇥ 2array and we select the first subwindow.13.8 ZoomingWe often need to “zoom in” on some portionof a plot in order to see more detail. Clickingon the “Zoom in” or “Zoom out” button on theFigure window is simplest but one can also usethe command>> zoomPointing the mouse to the relevant position onthe plot and clicking the left mouse button willzoom in by a factor of two. This may be repeatedto any desired level.Clicking the right mouse button will zoom outby a factor of two.Holding down the left mouse button and draggingthe mouse will cause a rectangle to be outlined.Releasing the button causes the contentsof the rectangle to fill the window.zoom off turns o↵ the zoom capability.Exercise 13.1 Draw graphs of the functionsy = cos xy = xfor 0 apple x apple 2 on the same window. Use thezoom facility to determine the point of intersectionof the two curves (and, hence, the rootof x = cos x) to two significant figures.13.9 Figure PropertiesAll plot properties can be edited from the Figurewindow by selecting the Edit and Toolsmenus from the toolbar. For instance, to changethe linewidth of a graph, click Edit and chooseFigure Properties... from the menu. Clickingon the required curve will display its attributeswhich can be readily modified.One of the shortcomings of editing the figurewindow in this way is the di culty of reproducingthe results at a later date. The recommendedalternative involves using commandsthat directly control the graphics properties.The current setting of any plot property can bedetermined by first obtaining its “handle number”,which is simply a real number that wesave to a named variable:>> plt = plot (x,y.^3,’k--o’)plt =188.0194and then using the get command. This lists thesettings for a number of properties that include>>get(plt)Color: [0 0 0]LineStyle: ’--’LineWidth: 1Marker:’o’MarkerSize: 6XData: [1 2 3]14


YData: [27 8 1]ZData:[1x0 double]The colour is described by a rgb triple in which[0 0 0] denotes black and [1 1 1] denoteswhite. Properties can be changed with the setcommand, for example>> set(plt,’markersize’,12)will change the size of the marker symbol ’o’while>> set(plt,’linestyle’,’:’,’ydata’,[1 8 27])will change the lifestyle from dashed to dottedwhile also changing the y–coordinates of thedata points. The commands>> x = 0:.01:1; y=sin(3*pi*x);>> plot(x,y,’k-’,x,cos(3*pi*x),’g--’)>> legend(’Sin curve’,’Cos curve’)>> title(’Multi-plot ’)>> xlabel(’x axis’), ylabel(’y axis’)>> set(gca,’fontsize’,16,...’ytick’,-1:.5:1);redraw Fig. 3 and the last line sets the fontsize to 16points and changes the tick-marks onthe y-axis to 1, 0.5, 0, 0.5, 1—see Fig. 4. The... in the penultimate line tell Matlab that theline is split and continues on the next line.Example 13.1 Plot the first 100 terms in thesequence {y n } given by y n = 1+ 1 nn and illustratehow the sequence converges to the limite = exp(1) = 2.7183.... as n !1.Exercises such as this that require a certainamount of experimentation are best carried outby saving the commands in a script file. Thecontents of the file (which we call latexplot.m)are:close allfigure(1);set(0,’defaultaxesfontsize’,12)set(0,’defaulttextfontsize’,16)set(0,’defaulttextinterpreter’,’latex’)N = 100; n = 1:N;y = (1+1./n).^n;subplot(2,1,1)plot(n,y,’.’,’markersize’,8)hold onaxis([0 N,2 3])plot([0 N],[1, 1]*exp(1),’--’)text(40,2.4,’$y_n = (1+1/n)^n$’)text(10,2.8,’y = e’)xlabel(’$n$’), ylabel(’$y_n$’)The results are shown in the upper part of Fig. 5.Fig. 4: Repeat of Fig. 3 with a font size of16points and amended tick marks on the y-axis.13.10 Formatted text on PlotsIt is possible to typeset simple mathematicalexpressions (using L A TEX commands) in labels,legends, axes and text. We shall give two illustrations.Fig. 5: The output from Example 13.1 (top)and Example 13.2 (bottom).The salient features of these commands are1. The set commands in lines 3–4 increasethe size of the default font size used for15


the axis labels, legends, titles and text.Line 4 tells Matlab to interpret any stringscontained within $ symbols as L A TEX commands.2. Defining a variable N = 100 makes it easierto experiment with a di↵erent numberof sampling points.3. The size of the plot symbol “.” is changedfrom the default (6) to size 8 by the additionalstring followed in the plot command.4. The axis command changes the dimensionsof the plotting area to be 0 apple x apple Nand 2 apple y apple 3.The axis command has four parameters,the first two are the minimum and maximumvalues of x to use on the axis andthe last two are the minimum and maximumvalues of y.5. The command text(40,2.4,’string’ )prints string at the location with coordinates(40 2.4).6. The string y_n gives subscripts: y n ,whilex^3 gives superscripts: x 3 .Example 13.2 Draw a graph the function y =e 3x2 sin 3 (3⇡x) on the interval 2 apple x apple 2.2. Greek characters ↵, ,...,!, ⌦ are producedby the strings ’\alpha’, ’\beta’,...,’\omega’, ’\Omega’. the integral symbol:R is produced by ’\int’.3. The thickness of the line used in the plotcommand is changed from its default value(0.5) to 2.4. The graphics are saved in jpeg format tothe file eplot1.13.11 Controlling AxesThe look of a graph can be changed by usingthe axis command. We have already seen inExample 13.1 how the plotting area can bechanged.axis equal is required in order that a circledoes not appear as an ellipse>> clf, N = 100; t = (0:N)*2*pi/N;>> x = cos(t); y = sin(t);>> plot(x,y,’-’,0,0,’.’);>> set(gca,’ytick’,-1:.5:1)>> axis equalSee Fig. 6. We recommend looking at helpaxis and experimenting with the commandsaxis equal, axis off, axis square,axis normal, axis tight in any order.The appropriate commands are included in thescript file for the previous example (so the defaultvalues continue to operate):subplot(2,1,2)x = -2:.01:2;y = exp(-3*x.^2).*sin(8*pi*x).^3;plot(x,y,’r-’,’linewidth’,1)xlabel(’$x$’), ylabel(’$y$’)text(-1.95,.75,’$ \exp(-40x^2)\sin^3(8\pi x)$’)print -djpeg90 eplot1The results are shown in the lower part of Fig. 5.1. sin 3 8⇡x is typeset by the L A TEX string$\sin^3 8\pi x$ and translates into theMatlab command sin(8*pi*x).^3—theposition of the exponent is di↵erent.Fig. 6: Use of axis equal to get a circle toappear correctly.16


14 Elementwise ExamplesExample 14.1 Draw graphs of the functionsi) y = sin xxii) u = 1(x 1)+ x 2iii) v = x2 +1x 2 4iv) w = (10 x)1/3 2(4 x 2 ) 1/2for 0 apple x apple 10.>> x = 0:0.1:10;>> y = sin(x)./x;>> subplot(221), plot(x,y), title(’(i)’)Warning: Divide by zero>> u = 1./(x-1).^2 + x;>> subplot(222),plot(x,u), title(’(ii)’)Warning: Divide by zero>> v = (x.^2+1)./(x.^2-4);>> subplot(223),plot(x,v),title(’(iii)’)Warning: Divide by zero>> w = ((10-x).^(1/3)-1)./sqrt(4-x.^2);Warning: Divide by zero>> subplot(224),plot(x,w),title(’(iv)’)Note the repeated use of the “dot” (elementwise)operators.Experiment by changing the axes (page 16),grids (page 12) and hold(page 13).>> subplot(222),axis([0 10 0 10])>> grid>> grid>> hold on>> plot(x,v,’--’), hold off,>> plot(x,y,’:’)Exercise 14.1 Tabulate the functionsandy =(x 2 + 3) sin ⇡x 2z =sin 2 ⇡x/(x 2 + 3)for x =0, 0.2,...,10. Hence, tabulate the functionw = (x2 + 3) sin ⇡x 2 sin 2 ⇡x(x 2 .+ 3)Plot a graph of w over the range 0 apple x apple 10.15 Two–Dimensional ArraysA rectangular array of numbers having m rowsand n columns is referred to as an m ⇥ n matrix.It is usual in a mathematical setting toenclose such objects in either round or squarebrackets—Matlab insists on square ones. Forexample, when m =2,n =3wehavea2⇥ 3matrix such asapple 5 7 9A =1 3 7To enter such an matrix into Matlab we typeit in row by row using the same syntax as forvectors:>> A = [5 7 91 -3 -7]A =5 7 91 -3 -7Rows may be separated by semi-colons ratherthan a new line:>> B = [-1 2 5; 9 0 5]B =-1 2 59 0 5>> C = [0, 1; 3, -2; 4, 2]C =0 13 -24 2>> D = [1:5; 6:10; 11:2:20]D =1 2 3 4 56 7 8 9 1011 13 15 17 1917


So A and B are 2 ⇥ 3 matrices, C is 3 ⇥ 2 and Dis 3 ⇥ 5.In this context, a row vector is a 1 ⇥ n matrixand a column vector a m ⇥ 1 matrix.15.1 Size of a matrixWe can get the size (dimensions) of a matrixwith the command size>> size(A), size(x)ans =2 3ans =3 1>> size(ans)ans =1 2So A is 2 ⇥ 3 and x is 3 ⇥ 1 (a column vector).The last command size(ans) shows that thevalue returned by size is itself a 1 ⇥ 2 matrix(a row vector). We can save the results for usein subsequent calculations.>> [r c] = size(A’), S = size(A’)r =3c =2S =3 2Arrays can be reshaped. A simple example is:>> A(:)ans =517-39-7which converts A into a column vector by stackingits columns on top of each other. This couldalso be achieved using reshape(A,6,1). Thecommand>> reshape(A,3,2)ans =5 -31 97 -7also redistributes the elements of A columnwise.15.2 Transpose of a matrixTransposing a vector changes it from a row to acolumn vector and vice versa (see §8.4)—recallthat is also performs the conjugate of complexnumbers. The extension of this idea to matricesis that transposing interchanges rows with thecorresponding columns: the 1st row becomesthe 1st column, and so on.>> D, D’D =1 2 3 4 56 7 8 9 1011 13 15 17 19ans =1 6 112 7 133 8 154 9 175 10 19>> size(D), size(D’)ans =3 5ans =5 315.3 Special MatricesMatlab provides a number of useful built–inmatrices of any desired size.ones(m,n) gives an m ⇥ n matrix of 1’s,>> P = ones(2,3)P =1 1 11 1 1zeros(m,n) gives an m ⇥ n matrix of 0’s,>> Z = zeros(2,3), zeros(size(P’))Z =0 0 00 0 0ans =0 018


0 00 0The second command illustrates how we canconstruct a matrix based on the size of an existingone. Try ones(size(D)).An n ⇥ n matrix that has the same numberof rows and columns and is called a squarematrix.A matrix is said to be symmetric if it is equalto its transpose (i.e. it is unchanged by transposition):>> S = [2 -1 0; -1 2 -1; 0 -1 2],S =2 -1 0-1 2 -10 -1 2>> St = S’St =2 -1 0-1 2 -10 -1 2>> S-Stans =0 0 00 0 00 0 015.4 The Identity MatrixThe n ⇥ n identity matrix is a matrix of zerosexcept for having ones along its leading diagonal(top left to bottom right). This is calledeye(n) in Matlab (since mathematically it isusually denoted by I).>> I = eye(3), x = [8; -4; 1], I*xI =1 0 00 1 00 0 1x =8-41ans =8-41Notice that multiplying the 3 ⇥ 1 vector x bythe 3 ⇥ 3 identity I has no e↵ect (it is like multiplyinga number by 1).15.5 Diagonal MatricesA diagonal matrix is similar to the identity matrixexcept that its diagonal entries are not necessarilyequal to 1.D =24 0 4 03 0 00 0 2is a 3 ⇥ 3 diagonal matrix. To construct this inMatlab, we could either type it in directly>> D = [-3 0 0; 0 4 0; 0 0 2]D =-3 0 00 4 00 0 2but this becomes impractical when the dimensionis large (e.g. a 100 ⇥ 100 diagonal matrix).We then use the diag function.We first define avector d, say, containing the values of the diagonalentries (in order) then diag(d) gives therequired matrix.>> d = [-3 4 2], D = diag(d)d =-3 4 2D =-3 0 00 4 00 0 2On the other hand, if A is any matrix, the commanddiag(A) extracts its diagonal entries:>> F = [0 1 8 7; 3 -2 -4 2; 4 2 1 1]F =0 1 8 73 -2 -4 24 2 1 1>> diag(F)ans =0-21Notice that the matrix does not have to besquare.3519


15.6 Building MatricesIt is often convenient to build large matricesfrom smaller ones:>> C=[0 1; 3 -2; 4 2]; x=[8;-4;1];>> G = [C x]G =0 1 83 -2 -44 2 1>> A, B, H = [A; B]A =5 7 91 -3 -7B =-1 2 59 0 5H =5 7 91 -3 -7-1 2 59 0 5so we have added an extra column (x) toC inorder to form G and have stacked A and B ontop of each other to form H.>> J = [1:4; 5:8; 9:12; 20 0 5 4]J =1 2 3 45 6 7 89 10 11 1220 0 5 4>> K = [ diag(1:4) J; J’ zeros(4,4)]K =1 0 0 0 1 2 3 40 2 0 0 5 6 7 80 0 3 0 9 10 11 120 0 0 4 20 0 5 41 5 9 20 0 0 0 02 6 10 0 0 0 0 03 7 11 5 0 0 0 04 8 12 4 0 0 0 0The command spy(K) will produce a graphicaldisplay of the location of the nonzero entries inK (it will also give a value for nz—the numberof nonzero entries):>> spy(K), gridThe keyword end can also be used with multidimensionalarraysK(1:2,end-1:end)ans =3 47 815.7 Tabulating FunctionsThis has been addressed in earlier sections butwe are now in a position to produce a moresuitable table format.Example 15.1Tabulate the functions y = 4sin3x and u =3 sin 4x for x =0, 0.1, 0.2,...,0.5.>> x = 0:0.1:0.5;>> y = 4*sin(3*x); u = 3*sin(4*x);>> [ x’ y’ u’]ans =0 0 00.1000 1.1821 1.16830.2000 2.2586 2.15210.3000 3.1333 2.79610.4000 3.7282 2.99870.5000 3.9900 2.7279Note the use of transpose (’) to get columnvectors. (we could replace the last commandby [x; y; u;]’)We could also have done this more directly:>> x = (0:0.1:0.5)’;>> [x 4*sin(3*x) 3*sin(4*x)]15.8 Extracting Parts of MatricesWe may extract sections from a matrix in muchthe same way as for a vector (page 6).Each element of a matrix is indexed accordingto which row and column it belongs to. Theentry in the ith row and jth column is denotedmathematically by A i,j and, in Matlab,by A(i,j). So>> JJ =1 2 3 45 6 7 820


9 10 11 1220 0 5 4>> J(1,1)ans =1>> J(2,3)ans =7>> J(4,3)ans =5>> J(4,5)??? Index exceeds matrix dimensions.>> J(4,1) = J(1,1) + 6J =1 2 3 45 6 7 89 10 11 127 0 5 4>> J(1,1) = J(1,1) - 3*J(1,2)J =-5 2 3 45 6 7 89 10 11 127 0 5 4In the following examples we extract i) the 3rdcolumn, ii) the 2nd and 3rd columns, iii) the4th row, and iv) the “central” 2 ⇥ 2 matrix.See §8.1.>> J(:,3) % 3rd columnans =37115>> J(:,2:3) % columns 2 to 3ans =2 36 710 110 5>> J(4,:) % 4th rowans =7 0 5 4>> % To get rows 2 to 3 & cols 2 to 3:>> J(2:3,2:3)ans =6 710 11Thus, : on its own refers to the entire columnor row depending on whether it is the first orthe second index.15.9 Elementwise Products (.*)The elementwise product works as for vectors:corresponding elements are multiplied together—so the matrices involved must have the samesize.>> A, BA =5 7 91 -3 -7B =-1 2 59 0 5>> A.*Bans =-5 14 459 0 -35>> A.*C??? Error using ==> .*Matrix dimensions must agree.>> A.*C’ans =0 21 361 6 -14Elementwise powers .^ and division ./ work inan analogous fashion.15.10 Matrix–vector productsWe turn next to the definition of the product ofa matrix with a vector. This product is only definedfor column vectors that have the samenumber of entries as the matrix has columns.So, if A is an m ⇥ n matrix and x is a columnvector of length n, then the matrix–vector Axis legal.An m ⇥ n matrix times an n ⇥ 1 matrix ) am ⇥ 1 matrix.We visualise A as being made up of m row vectorsstacked on top of each other, then the productcorresponds to taking the inner product21


(See §12.1) of each row of A with the vector x:The result is a column vector with m entries." # 2 35 7 986 7Ax =4 4 51 3 71apple5 ⇥ 8+7⇥ ( 4) + 9 ⇥ 1=1 ⇥ 8+( 3) ⇥ ( 4) + ( 7) ⇥ 1apple 21=13It is somewhat easier in Matlab:>> A = [5 7 9; 1 -3 -7]A =5 7 91 -3 -7>> x = [8; -4; 1]x =8-41>> A*xans =2113(m⇥ n) times(n ⇥1) ) (m ⇥ 1).>> x*A??? Error using ==> *Inner matrix dimensions must agree.Unlike multiplication in scalar arithmetic, A*xis not the same as x*A.15.11 Matrix–Matrix ProductsTo form the product of an m ⇥ n matrix A anda n ⇥ p matrix B, written as AB, we visualisethe first matrix (A) as being composed of mrow vectors of length n stacked on top of eachother while the second (B) is visualised as beingmade up of p column vectors of length n:823 2 3>:| {z }p columnsThe entry in the ith row and jth column of theproduct is then the innerproduct of the ith rowof A with the jth column of B. Theproductisan m ⇥ p matrix:(m⇥ n) times(n ⇥p) ) (m ⇥ p).Check that you understand what is meant byworking out the following examples by handand comparing with the Matlab answers.>> A = [5 7 9; 1 -3 -7]A =5 7 91 -3 -7>> B = [0, 1; 3, -2; 4, 2]B =0 13 -24 2>> C = A*BC =57 9-37 -7>> D = B*AD =1 -3 -713 27 4122 22 22>> E = B’*A’E =57 -379 -7We see that E = C’ suggesting that(A*B)’ = B’*A’Why is B ⇤A a3⇥3 matrix while A⇤B is 2⇥2?Exercise 15.1 It is often necessary to factorizea matrix, e.g., A = BC or A = S T XSwhere the factors are required to have specificproperties. Use the ’lookfor keyword’ commandto make a list of factorizations commandsin Matlab.22


15.12 Sparse MatricesMatlab has powerful techniques for handlingsparse matrices — these are generally large matrices(to make the extra work involved worthwhile)that have only a very small proportionof non–zero entries.Example 15.2 Create a sparse 5 ⇥ 4 matrixS having only 3 non–zero values: S 1,2 = 10,S 3,3 = 11 and S 5,4 = 12.We first create 3 vectors containing the i–index,the j–index and the corresponding values ofeach term and we then use the sparse command.>> i = [1, 3, 5]; j = [2,3,4];>> v = [10 11 12];>> S = sparse (i,j,v)S =(1,2) 10(3,3) 11(5,4) 12>> T = full(S)T =0 10 0 00 0 0 00 0 11 00 0 0 00 0 0 12The matrix T is a “full” version of the sparsematrix S.Example 15.3 Develop Matlab code to create,for any given value of n, the sparse (tridiagonal)matrix2B =641 n 12 2 n 23 3 n 3. .. . .. . ..n +1 n 1 1n nWe define three column vectors, one for each“diagonal” of non–zeros and then assemble thematrix using spdiags (short for sparse diagonals).The vectors are named l (lower diagonal),d (diagonal) and u (upper diagonal). Theymust all have the same length and only the firstn 1 terms of l are used while the last n 1terms of u are used. spdiags places these vectorsin the diagonals labelled -1, 0 and 1 (0defers to the leading diagonal, negatively numbereddiagonals lie below the leading diagonal,etc.)>> n = 5;>> d = (1:n)’; l = -(d+1)’;>> u = flipud(d’)>> B = spdiags([l d u],-1:1,n,n);>> full(B)ans =1 4 0 0 0-2 2 3 0 00 -3 3 2 00 0 -4 4 10 0 0 -5 5Notice the use of the command flipud thatreverses the entries in a column vector. Moregenerally flipudreverses the order of rows in amatrix (two dimensional array), while fliplrreverses the order of columns.16 Systems of Linear EquationsMathematical formulations of engineering problemsoften lead to sets of simultaneous linearequations.A general system of linear equations can be expressedin terms of a coe cient matrix A, aright-hand-side (column) vector b and an unknown(column) vector x as3Ax = bor, componentwise, as7 a 1,1 x 1 + a 1,2 x 2 + ···a 1,n x n = b 15a 2,1 x 1 + a 2,2 x 2 + ···a 2,n x n = b 2a n,1 x 1 + a n,2 x 2 + ···a n,n x n = b nWhen A is non-singular and square (n ⇥ n),meaning that the number of independent equationsis equal to the number of unknowns, the.23


system has a unique solution given by Exercise 16.2 Use the backslash operator tox = A 1 solve the complex system of equations for whichb23 2 3where A 1 2 + 2i 1 01+iis the inverse of A. Thus, the solutionvector x can, in principle, be calculated byA = 4 1 2 2i 1 5 , b = 4 0 50 1 21 itaking the inverse of the coe cient matrix Aand multiplying it on the right with the righthand-sidevector b.Exercise 16.3 Find information on the matrixinversion command ’inv’ using each of theThis approach based on the matrix inverse, thoughmethods listed in Section 2 for obtaining help.formally correct, is at best ine cient for practicalapplications (where the number of equa-What kind of matrices are the ’inv’ commandapplicable to?tions may be extremely large) but may also giveObviously problems may occur if the invertedrise to large numerical errors unless appropriatetechniques are used. These issues are dis-matrix is nearly singular. Suggest a commandthat can be used to give an indication on whethercussed in most courses and texts on numericalthe matrix is nearly singular or not. [Hint: seemethods. Various stable and e cient solutionthe topics referred to by ’help inv’.]techniques have been developed for solving linearequations and the most appropriate in anysituation will depend on the properties of the 16.1 Overdetermined systemscoe cient matrix A. For instance, on whetheror not it is symmetric, or positive definite orif it has a particular structure (sparse or full).Matlab is equipped with many of these specialtechniques in its routine library and many areinvoked automatically.The standard Matlab routine for solving systemsof linear equations is invoked by callingthe matrix left-division routine,>> x = A \ bwhere “\” is the matrix left-division operatorknown as “backslash” (see help backslash).Exercise 16.1 Enter the symmetric coe cientmatrix and right–hand–side vector b given by22 130213A = 4 1 2 1 5 , b = 4 0 50 1 21and solve the system of equations Ax = b usingthe three alternative methods:i) x = A 1 b, (the inverse A 1 may be computedin Matlab using inv(A).)ii) x = A \ b,iii) x T A T = b T leading to xT = b’ / A whichmakes use of the “slash” or “right division”operator “/”. The required solutionis then the transpose of the row vector xT.An overdetermined system of linear equations isa one with more equations (m) than unknowns(n), i.e., the coe cient matrix has more rowsthan columns (m >n). Overdetermined systemsfrequently appear in mathematical modellingwhen the parameters of a model are determinedby fitting to experimental data. Formallythe system looks the same as for squaresystems but the coe cient matrix is rectangularand so it is not possible to compute an inverse.In these cases a solution can be foundby requiring that the magnitude of the residualvector r, definedbyr = Ax b,be minimized. The simplest and most frequentlyused measure of the magnitude of r is requirethe Euclidean length (or norm—see Section 12.1)which corresponds to the sum of squares of thecomponents of the residual. This approach leadsto the least squares solution of the overdeterminedsystem. Hence the least squares solutionis defined as the vector x that minimizesr T r.It may be shown that the required solution satisfiesthe so–called “normal equations”Cx = d, where C = A T A and d = A T b.24


It is well–known that the solution of this systemcan be overwhelmed by numerical rounding errorin practice unless great care is taken in itssolution (a large part of the di culty is inherentin the loss of information in computing thematrix–matrix product A T A). As in the solutionof square systems of linear equations, specialtechniques have been developed to addressthese issues and they have been incorporatedinto the Matlab routine library.This means that a direct solution to the problemof overdetermined equations is available inMatlab through its left division operator “\”.When the matrix A is not square, the operationForce F [N] Deformation x [cm]5 0.00150 0.011500 0.0131000 0.302000 0.75Table 1: Measured force-deformation data forspring.byr 1 = x 1 k 1 + x 2 1k 2 F 1r 2 = x 2 k 1 + x 2 2k 2 F 2x = A\bautomatically gives the least squares solutionto Ax = b. This is illustrated in the next example.Example 16.1 A spring is a mechanical elementwhich, for the simplest model, is characterizedby a linear force-deformation relationshipF = kx,F being the force loading the spring, k the springconstant or sti↵ness and x the spring deformation.In reality the linear force–deformation relationshipis only an approximation, valid forsmall forces and deformations. A more accuraterelationship, valid for larger deformations,is obtained if non–linear terms are taken intoaccount. Suppose a spring model with a quadraticrelationshipF = k 1 x + k 2 x 2is to be used and that the model parameters,k 1 and k 2 , are to be determined from experimentaldata. Five independent measurementsof the force and the corresponding spring deformationsare measured and these are presentedin Table 1.Using the quadratic force-deformation relationshiptogether with the experimental data yieldsan overdetermined system of linear equationsand the components of the residual are givenr 3 = x 3 k 1 + x 2 3k 2 F 3r 4 = x 4 k 1 + x 2 4k 2 F 4r 5 = x 5 k 1 + x 2 5k 2 F 5 .These lead to the matrix and vector definitions2 3 2 3x 1 x 2 1F 1x 2 x 2 2A =6 x 3 x 2 3 74 x 4 x 2 5 and b = F 26 F 3744F 45x 5 x 2 5F 5 .The appropriate Matlab commands give (thecomponents of x are all multiplied by 1e-2, i.e.,10 2 , in order to change from cm to m)>> x = [.001 .011 .13 .3 .75]*1e-2;>> A = [x’ (x’).^2]A =0.0000 0.00000.0001 0.00000.0013 0.00000.0030 0.00000.0075 0.0001>> format short e>> AA =1.0000e-05 1.0000e-101.1000e-04 1.2100e-081.3000e-03 1.6900e-063.0000e-03 9.0000e-067.5000e-03 5.6250e-05>> format, format compact>> b = [5 50 500 1000 2000];The second column of A is mainly zeros in standardformat and so a switch to format short25


e is used the least squares solution to this systemis given by>> k = A\b’k =1.0e+07 *0.0386-1.5993apple0.39Thus, k ⇡⇥ 1016.06 and the quadraticspring force-deformation relationship that optimallyfits experimental data in the least squaressense isF ⇡ 38.6 ⇥ 10 4 x 16.0 ⇥ 10 6 x 2 .The data and solution may be plotted with thefollowing commands>> % plot data points>> plot(x,f,’o’), hold on>> X = (0:.01:1)*max(x);>> % best fit curve>> plot(X,[X’ (X.^2)’]*k,’-’)>> xlabel(’x[m]’), ylabel(’F[N]’)and the results are shown in Fig. 7.17 Characters, Strings andTextThe ability to process text in numerical processingis useful for the input and output ofdata to the screen or to files. In order to managetext, a new datatype of “character” is introduced.A piece of text is then simply a string(vector) or array of characters.Example 17.1 The assignment,>> t1 = ’A’assigns the value A to the 1-by-1 character arrayt1. The assignment,>> t2 = ’BCDE’t2 =BCDE>> size(t2)ans =1 4assigns the value BCDE to the 1-by-4 characterarray t2.Strings can be combined by using the operationsfor array manipulations.The assignment,>> t3 = [t1,t2]assigns a value ABCDE to the 1-by-5 characterarray t3. The assignment,>> t4 = [t3,’ are the first 5 ’;...’characters in the alphabet.’]Fig. 7: Data for Example 16.1 (circles) and bestleast squares fit by a quadratic model (solidline).Matlab has a routine polyfit for data fittingby polynomials: see “help polyfit”. It is notapplicable in this example because we requirethat the force – deformation law passes throughthe origin (so there is no constant term in thequadratic model that we used).assigns the value’ABCDE are the first 5 ’’characters in the alphabet.’to the 2-by-27 character array t4. Itisessentialthat the number of characters in both rowsof the array t4 is the same, otherwise an errorwill result. The three dots ... signify that thecommand is continued on the following lineSometimes it is necessary to convert a characterto the corresponding number, or vice versa.These conversions are accomplished by the commands’str2num’—which converts a string to26


the corresponding number, and two functions,’int2str’ and ’num2str’, which convert, respectively,an integer and a real number to the correspondingcharacter string. These commandsare useful for producing titles and strings, suchas ’The value of pi is 3.1416’. This can begenerated by the command[’The value of pi is ’,num2str(pi)].>> N = 5; h = 1/N;>> [’The value of N is ’,int2str(N),...’, h = ’,num2str(h)]ans =The value of N is 5, h = 0.2>> F(1) = 0; F(2) = 1;>> for i = 3:20F(i) = F(i-1) + F(i-2);end>> plot(1:19, F(1:19)./F(2:20),’o’ )>> hold on, xlabel(’n’)>> plot(1:19, F(1:19)./F(2:20),’-’ )>> legend(’Ratio of terms f_{n-1}/f_n’)>> plot([0 20], (sqrt(5)-1)/2*[1,1],’--’)The last of these commands produces the dashedhorizontal line.18 LoopsThere are occasions that we want to repeat asegment of code a number of di↵erent times(such occasions are less frequent than other programminglanguages because of the : notation).A standard for loop has the form>> for counter = 1:20.......endwhich repeats the code as far as the end withthe variable counter=1 the first time, counter=2the second time, and so forth. Rather moregenerally>> for counter = [23 11 19 5.4 6].......endrepeats the code with counter=23 the first time,counter=11 the second time, and so forth.Example 18.1 The Fibonnaci sequence startso↵ with the numbers 0 and 1, then succeedingterms are the sum of its two immediate predecessors.Mathematically, f 1 =0, f 2 =1andf n = f n 1 + f n 2 , n =3, 4, 5,....Test the assertion that the ratio f n 1 /f n of twosuccessive values approaches the golden ratio( p 5 1)/2 =0.6180 ....Example 18.2 Produce a list of the values ofthe sumsS 20 = 1+ 1 2 2 + 1 3 2 + ···+ 120 2S 21 = 1+ 1 2 2 + 1 3 2 + ···+ 120 2 + 121 2.S 100 = 1+ 1 2 2 + 1 3 2 + ···+ 120 2 + 121 2 + ···+ 1100 2There are a total of 81 sums. The first canbe computed using sum(1./(1:20).^2) (Thefunction sum with a vector argument sums itscomponents. See §21.2].) A suitable piece ofMatlab code might be>> S = zeros(100,1);>> S(20) = sum(1./(1:20).^2);>> for n = 21:100>> S(n) = S(n-1) + 1/n^2;>> end>> clf; plot(S,’.’,[20 100],[1,1]*pi^2/6,’-’)>> axis([20 100 1.5 1.7])>> [ (98:100)’ S(98:100)]ans =98.0000 1.636427


99.0000 1.6365100.0000 1.6366where a column vector S was created to hold theanswers. The first sum was computed directlyusing the sum command then each succeedingsum was found by adding 1/n 2 to its predecessor.The little table at the end shows thevalues of the last three sums—it appears thatthey are approaching a limit (the value of thelimit is ⇡ 2 /6=1.64493 ...).A more elegant solution is given by>> n = 1:100;>> S = cumsum(1./n.^2);where cumsum calculates the cumulative sum ofentries in a vector.Exercise 18.1 Repeat Example 18.2 to include181 sums (i.e., the final sum should include theterm 1/200 2 .)19 TimingMatlab allows the timing of sections of codeby providing the functions tic and toc. ticswitches on a stopwatch while toc stops it andreturns the CPU time (Central Processor Unit)in seconds. The timings will vary dependingon the model of computer being used and itscurrent load.>> tic, sum((1:10000).^2);tocElapsed time is 0.000124 seconds.>> tic, sum((1:10000).^2);tocElapsed time is 0.000047 seconds.>> tic, s = sum((1:10000).^2);T = tocT =8.2059e-05The first two instances illustrate that there canbe considerable variation in successive calls tothe same operations. The third instance showsthat the elapsed time can be assigned to a variable.20 LogicalsMatlab represents true and false by means ofthe integers 0 and 1.true = 1, false = 0If at some point in a calculation a scalar x, say,has been assigned a value, we may make certainlogical tests on it:x == 2 is x equal to 2?x ~= 2 is x not equal to 2?x > 2 is x greater than 2?x < 2 is x less than 2?x >= 2 is x greater than or equal to 2?x > x = pix =3.1416>> x ~= 3, x ~= pians =1ans =0When x is a vector or a matrix, these tests areperformed elementwise:x =-2.0000 3.1416 5.0000-1.0000 0 1.0000>> x == 0ans =0 0 00 1 0>> x > 1, x >=-1ans =0 1 10 0 0ans =0 1 11 1 1>> y = x>=-1, x > yy =0 1 11 1 1ans =0 1 10 0 0We may combine logical tests, as in>> xx =28


-2.0000 3.1416 5.0000-5.0000 -3.0000 -1.0000>> x > 3 & x < 4ans =0 1 00 0 0>> x > 3 | x == -3ans =0 1 10 1 0As one might expect, & represents and and (notso clearly) the vertical bar | means or; also ~means not as in ~= (not equal), ~(x>0), etc.>> x > 3 | x == -3 | x > x, L = x >= 0x =-2.0000 3.1416 5.0000-5.0000 -3.0000 -1.0000L =0 1 10 1 1>> pos = x.*Lpos =0 3.1416 5.00000 0 0so the matrix pos contains just those elementsof x that are non–negative.>> x = 0:0.05:6; y = sin(pi*x);>> Y = (y>=0).*y;>> plot(x,y,’:’,x,Y,’-’ )20.1 While LoopsThere are some occasions when we want to repeata section of Matlab code until some logicalcondition is satisfied, but we cannot tell in advancehow many times we have to go aroundthe loop. This we can do with a while...endconstruct.Example 20.1 What is the greatest value of nthat can be used in the sum1 2 +2 2 + ···+ n 2and get a value of less than 100?>> S = 1; n = 2;>> while S+ n^2 < 100S = S + n^2; n = n+1;end>> [n-1, S]ans =6 91The lines of code between while and end willonly be executed if the condition S+n^2 < 100is true.Exercise 20.1 Replace 100 in the previous exampleby 10 and work through the lines of codeby hand. You should get the answers n =2andS =5.Exercise 20.2 Type the code from Example20.1into a script–file named WhileSum.m (See §10.)A more typical example isExample 20.2 Find the approximate value ofthe root of the equation x = cos x. (SeeExample13.1.)We may do this by making a guess x 1 = ⇡/4,say, then computing the sequence of valuesx n = cos x n 1 , n =2, 3, 4,...and continuing until the di↵erence, d, betweentwo successive values |x n x n 1 | is small enough.29


Method 1:>> x = zeros(1,20); x(1) = pi/4;>> n = 1; d = 1;>> while d > 0.001n = n+1; x(n) = cos(x(n-1));d = abs( x(n) - x(n-1) );endn,x(1:n)n =14x =Columns 1 through 60.7854 0.7071 0.7602 0.7247 0.7487 0.7326Columns 7 through 120.7435 0.7361 0.7411 0.7377 0.7400 0.7385Columns 13 through 140.7395 0.7388There are a number of deficiencies with thisprogram. The vector x stores the results ofeach iteration but we don’t know in advancehow many there may be. In any event, we arerarely interested in the intermediate values ofx, only the last one. Another problem is thatwe may never satisfy the condition d apple 0.001,in which case the program will run forever, sowe should place a limit on the maximum numberof iterations.Incorporating these improvements leads toMethod 2:>> xold = pi/4; n = 1; d = 1;>> while d > 0.001 & n < 20n = n+1; xnew = cos(xold);d = abs( xnew - xold );xold = xnew;end>> [n, xnew, d]ans =14.0000 0.7388 0.0007We continue around the loop so long as d>0.001 and n0.0001, and thisgives>> [n, xnew, d]ans =19.0000 0.7391 0.0001from which we may judge that the root requiredis x =0.739 to 3 decimal places.The general form of while statement iswhile a logical testCommands to be executedwhen the condition is trueend20.2 if...then...else...endThis allows us to execute di↵erent commandsdepending on the truth or falsity of some logicaltests. To test whether or not ⇡ e is greater than,or equal to, e ⇡ :>> a = pi^exp(1); c = exp(pi);>> if a >= cb = sqrt(a^2 - c^2)endso that b is assigned a value only if a c. Thereis no output so we deduce that a = ⇡ e > if a >= cb = sqrt(a^2 - c^2)elseb = 0endb =0which ensures that b is always assigned a valueand confirming that a> if a >= cb = sqrt(a^2 - c^2)elseif a^c > c^ab = c^a/a^celseb = a^c/c^aendb =0.2347Exercise 20.3 Which of the above statementsassigned a value to b?The general form of the if statement is30


if logical test 1Commands to be executed if test 1is trueelseif logical test 2Commands to be executed if test 2is true but test 1 is falseend.>> A = [1:3; 4:6; 7:9]A =1 2 34 5 67 8 9>> s = sum(A), ss = sum(sum(A))s =12 15 18ss =4521 Further Built–in Functions21.1 Rounding NumbersThere are a variety of ways of rounding andchopping real numbers to give integers. Use thedefinitions given in the table in §26 on page 42in order to understand the output given below:>> x = [-4 -1 1 4]*pix =-12.5664 -3.1416 3.1416 12.5664>> round(x)ans =-13 -3 3 13>> fix(x)ans =-12 -3 3 12>> floor(x)ans =-13 -4 3 12>> ceil(x)ans =-12 -3 4 13>> sign(x), rem(x,3)ans =-1 0 1 1 1ans =-0.5664 -0.1416 0.1416 0.5664Do “help round” for help information.21.2 The sum FunctionThe “sum” applied to a vector adds up its components(as in sum(1:10)) while, for a matrix,it adds up the components in each columnand returns a row vector. sum(sum(A)) thensums all the entries of A.>> x = pi/4*(1:3)’;>> A=[sin(x),sin(2*x),sin(3*x)]/sqrt(2)>> A =0.5000 0.7071 0.50000.7071 0.0000 -0.70710.5000 -0.7071 0.5000>> s1 = sum(A.^2), s2 = sum(sum(A.^2))s1 =1.0000 1.0000 1.0000s2 =3.0000The sums of squares of the entries in each columnof A are equal to 1 and the sum of squaresof all the entries is equal to 3.>> A*A’ans =1.0000 0 00 1.0000 0.00000 0.0000 1.0000>> A’*Aans =1.0000 0 00 1.0000 0.00000 0.0000 1.0000It appears that the products AA 0 and A 0 A areboth equal to the identity:>> A*A’ - eye(3)ans =1.0e-15 *-0.2220 0 00 -0.2220 0.05550 0.0555 -0.2220>> A’*A - eye(3)ans =1.0e-15 *31


-0.2220 0 00 -0.2220 0.05550 0.0555 -0.2220This is confirmed since the di↵erences are atround–o↵ error levels (less than 10 15 ). A matrixwith this property is called an orthogonalmatrix.21.3 max & minThese functions act in a similar way to sum. Ifx is a vector, then max(x) returns the largestelement in x>> x = [1.3 -2.4 0 2.3]x =1.3000 -2.4000 0 2.3000>> max(x), max(abs(x))ans =2.3000ans =2.4000>> [m, j] = max(x)m =2.3000j =4Repeating these commands will lead to di↵erentanswers. Example 22.2 gives an illustrationof the use of random numbers.21.5 find for vectorsThe function “find” returns a list of the positions(indices) of the elements of a vector satisfyinga given condition. For example,>> x = -1:.05:1;>> y = sin(3*pi*x).*exp(-x.^2);>> plot(x,y,’:’)>> k = find(y > 0.2)k =Columns 1 through 129 10 11 12 13 22 23 24 25 26 27 36Columns 13 through 1537 38 39>> hold on, plot(x(k),y(k),’o’)>> km = find( x>0.5 & y> plot(x(km),y(km),’-’)When we ask for two outputs, the first gives usthe maximum entry and the second the indexof the maximum element.For a matrix, A, max(A) returns a row vectorcontaining the maximum element from eachcolumn. Thus, to find the largest element in A,we use max(max(A)).21.4 Random NumbersThe function rand(m,n) produces an m⇥n matrixof random numbers, each of which is in therange 0 to 1. rand on its own produces a singlerandom number.>> y = rand, Y = rand(2,3)y =0.9191Y =0.6262 0.1575 0.25200.7446 0.7764 0.612121.6 find for matricesThe find–function operates in much the sameway for matrices:>> A = [ -2 3 4 4; 0 5 -1 6; 6 8 0 1]A =-2 3 4 40 5 -1 632


6 8 0 1>> k = find(A==0)k =29Thus, we find that A has elements equal to 0 inpositions 2 and 9. To interpret this result wehave to recognize that “find” first reshapes Ainto a column vector (see §15.1)—this is equivalentto numbering the elements of A by columnsas in1 4 7 102 5 8 113 6 9 12>> n = find(A > A(n)ans =-20-10Thus, n gives a list of the locations of the entriesin A that are apple 0 and then A(n) gives us thevalues of the elements selected.>> m = find( A’ == 0)m =511Since we are dealing with A’, the entries arenumbered by rows.22 Function m–filesWe can extend the number of Matlab built-infunctions by writing our own. They are specialcases of m–files (§7).Example 22.1 The area, A, of a triangle withsides of length a, b and c is given byA = p s(s a)(s b)(s c),where s =(a+b+c)/2. Write a Matlab functionthat will accept the values a, b and c as inputsand return the value of A as output.The main steps to follow when defining a Matlabfunction are:1. Decide on a name for the function, makingsure that it does not conflict with aname that is already used by Matlab. Inthis example the name of the function isto be area, so its definition will be savedin a file called area.m2. The first line of the file must have theformat:function [list of outputs]= function name(list of inputs)For our example, the output (A)isafunctionof the three variables (inputs) a, band c so the first line should readfunction [A] = area(a,b,c)3. Document the function. That is, describebriefly the purpose of the function andhow it can be used. These lines should bepreceded by % which signify that they arecomment lines that will be ignored whenthe function is evaluated.4. Finally include the code that defines thefunction. This should be interspersed withsu cient comments to enable another userto understand the processes involved.The complete file might look like:function [A] = area(a,b,c)% Compute the area of a triangle whose% sides have length a, b and c.% Inputs:% a,b,c: Lengths of sides% Output:% A: area of triangle% Usage:% Area = area(2,3,4);% Written by dfg, Oct 14, 1996.s = (a+b+c)/2;A = sqrt(s*(s-a)*(s-b)*(s-c));%%%%%%%%% end of area %%%%%%%%%%%33


The command>> help areawill produce the leading comments from thefile:Compute the area of a triangle whosesides have length a, b and c.Inputs:a,b,c: Lengths of sidesOutput:A: area of triangleUsage:Area = area(2,3,4);Written by dfg, Oct 14, 1996.To evaluate the area of a triangle with side oflength 10, 15, 20:>> Area = area(10,15,20)Area =72.6184where the result of the computation is assignedto the variable Area—the use of a capitalisedvariable name is critical here, otherwise therewould be confusion between the variable nameand the function name. If we inadvertently usea variable name that coincides with a functionname, as in>> sin = sin(pi/6)sin =0.5000>> sin(pi/2)??? Subscript indices must either bereal positive integers or logicals.Matlab now considers the name sin to refer toa variable and pi/2 in the command sin(pi/2)is interpreted as an index to a vector. To reclaimthe function name we clear the variablesin from memory with>> clear sinThe variable s used in the definition of the areafunction above is a “local variable”: its value islocal to the function and cannot be used outside:>> s??? Undefined function or variable s.If we were interested in the value of s as wellas A, then the first line of the file should bechanged tofunction [A,s] = area(a,b,c)where there are two output variables.This function can be called in several di↵erentways:1. No outputs assigned>> area(10,15,20)ans =72.6184gives only the area (first of the outputvariables from the file) assigned to ans;the second output is ignored.2. One output assigned>> Area = area(10,15,20)Area =72.6184again the second output is ignored.3. Two outputs assigned>> [Area, hlen] = area(10,15,20)Area =72.6184hlen =22.5000The previous examples illustrate the fact thata function may have a di↵erent number of outputs.It is also possible to write function filesthat accepts a variable number of inputs. Forexample, in the context of our area function,to calculate the area of a right angled triangle itis only necessary to specify the lengths of twoof the sides since the third (the hypotenuse)can be calculated by Pythagoras’s theorem. Soour amended function operates as previouslydescribed but, when only two input argumentsare supplied, it assumes the triangle to be rightangled. It does this by using the reserved variablenargin that holds the number of input arguments.The revised function, called area2,might then resemble the following code:34


function [A] = area2(a,b,c)% Compute the area of a triangle whose% sides have length a, b and c.% Inputs: either% a,b,c: Lengths of 3 sides% or% a, b: two shortest sides of a% right angled triangle% Output:% A: area of triangle% Usage:% Area = area2(2,3,4);% or% Area = area2(3,4);% Written by dfg, Oct 14, 1996.% Extended Oct 25, 2012if nargin > dice(3)ans =6 12 34 1>> sum(dice(100))/100ans =3.8500 3.4300The last command gives the average value over100 throws (it should theoretically have the value3.5).Example 22.3 Construct a function that willreturn the nth Fibonnaci number f n , wheref 1 =0,f 2 =1andf n = f n 1 + f n 2 , n =3, 4, 5,....(See Example 18.1.) The function has:• Input: Non-negative integer n• Output: f nWe shall describe four possible functions andtry to assess which provides the best solution.Method 1:File Fib1.mfunction f = Fib1(n)% Returns the nth number in the% Fibonacci sequence.F = zeros(1,n);F(2) = 1;for i = 3:nF(i) = F(i-1) + F(i-2);endf = F(n);35


This code resembles that given in Example 18.1.We have simply enclosed it in a function m–fileand given it the appropriate header. The mostsignificant change is the line F=zeros(1,n) whichserves to both define the value of F(1) and toallocate su cient memory to store a vector tohold the first n Fibonacci numbers. Had we notdone this then the length of the vector F wouldbe extended on each trip around the loop andmore memory would have to be allocated forits storage. The time penalties this would incurwould not be significant in this example (since,with modest values of n, it computes in a tinyfraction of a second) but could be importantwhen dealing with large arrays in codes thatare run many times over.Method 2: File Fib2.mThe first version was rather wasteful of memory,all the entries in the sequence where savedeven though we only required the last one foroutput. The second version removes the needto use a vector.function f = Fib2(n)% Returns the nth number in the% Fibonacci sequence.if n==1f = 0;elseif n==2f = 1;elsef1 = 0; f2 = 1;for i = 3:nf = f1 + f2;f1 = f2; f2 = f;endendMethod 3: File: Fib3.mThis version makes use of an idea called “recursiveprogramming”—the function makes callsto itself.function f = Fib3(n)% Returns the nth number in the% Fibonacci sequence.if n==1f = 0;elseif n==2f = 1;elsef = Fib3(n-1) + Fib3(n-2);endMethod 4: File Fib4.mThe final version uses matrix powers. apple The vectory has two components, y = .fnf n+1function f = Fib4(n)% Returns the nth number in the% Fibonacci sequence.A = [0 1;1 1];y = A^n*[1;0];f=y(1);Assessment: One may think that, on groundsof style, the 3rd is best (it avoids the use ofloops) followed by the second (it avoids the useof a vector). The situation is somewhat di↵erentwhen it comes to speed of execution. Whenn = 20 the time taken by each of the methodsis (in seconds)Method Time1 5.8052 ⇥ 10 52 2.5534 ⇥ 10 53 1.4972 ⇥ 10 14 5.4041 ⇥ 10 5What is immediately obvious from these timingsis that Method 3 is significantly slowerthan the others. Moreover, the time increasesdramatically as n is increased and is totally impractical.Methods 1, 2, and 4 execute veryrapidly and the times increase quite slowly asn is increased. When times are averaged overmany hundreds of runs it becomes clear thatMethod 2 is the most e cient followed by Method 1.23 Plotting SurfacesA surface is defined mathematically by a functionf(x, y)—corresponding to each value of (x, y)we compute the height of the function byz = f(x, y).36


In order to plot this we have to decide on theranges of x and y—suppose 2 apple x apple 4 and1 apple y apple 3. This gives us a square in the (x, y)–plane. Next, we need to choose a grid on thisdomain; Figure 8 shows the grid with intervals0.5 in each direction. Finally, we have to eval-as corresponding to the (i, j)th entry in a matrix,then (X(i,j), Y(i,j)) are the coordinates of thepoint. We then need to evaluate the function f usingX and Y in place of x and y, respectively. Asin Example 14.1, elementwise operations (powers,products, etc.) are usually appropriate.Example 23.1 Plot the surface defined by the functionf(x, y) =(x 3) 2 (y 2) 2for 2 apple x apple 4 and 1 apple y apple 3.>> [X,Y] = meshgrid(2:.2:4, 1:.2:3);>> Z = (X-3).^2-(Y-2).^2;>> mesh(X,Y,Z)>> title(’Saddle’), xlabel(’x’),ylabel(’y’)Fig. 8: An example of a 2D griduate the function at each point of the grid and“plot” it.Suppose we choose a grid with intervals 0.5 ineach direction for illustration. The x– and y–coordinates of the grid lines arex = 2:0.5:4; y = 1:0.5:3;in Matlab notation. We construct the grid withmeshgrid:Fig. 9: Plot of Saddle function.>> [X,Y] = meshgrid(2:.5:4, 1:.5:3);>> XExercise 23.1 Repeat the previous example replacingmesh by surf and then by surfl. Consult theX =2.0000 2.5000 3.0000 3.5000 4.0000 help pages to find out more about these functions.2.0000 2.5000 3.0000 3.5000 4.0000Example 23.2 Plot the surface defined by the function2.0000 2.5000 3.0000 3.5000 4.00002.0000 2.5000 3.0000 3.5000 4.0000f = xye 2(x2 +y 2 )2.0000 2.5000 3.0000 3.5000 4.0000>> Yon the domain 2 apple x apple 2, 2 apple y apple 2. Find theY =1.0000 1.0000 1.0000 1.0000values and locations of the maxima and minima of1.0000 the function.1.5000 1.5000 1.5000 1.5000 1.50002.0000 2.0000 2.0000 2.0000 2.0000 >> [X,Y] = meshgrid(-2:.1:2,-2:.2:2);2.5000 2.5000 2.5000 2.5000 2.5000 >> f = -X.*Y.*exp(-2*(X.^2+Y.^2));3.0000 3.0000 3.0000 3.0000 3.0000 >> figure (1)If we think of the ith point along from the leftand the jth point up from the bottom of the grid)>> mesh(X,Y,f), xlabel(’x’), ylabel(’y’), grid>> figure (2), contour(X,Y,f)>> xlabel(’x’), ylabel(’y’), grid, hold on37


Fig. 11: contour plot showing maxima.24 Reading/Writing Data FilesFig. 10: “mesh” and “contour” plots.To locate the maxima of the “f” values on the grid:>> fmax = max(max(f))fmax =0.0886>> kmax = find(f==fmax)kmax =323539>> Pos = [X(kmax), Y(kmax)]Pos =-0.5000 0.60000.5000 -0.6000>> plot(X(kmax),Y(kmax),’*’)>> text(X(kmax),Y(kmax),’ Maximum’)See §13.10 for formatting text and labels.Direct input of data from keyboard becomes impracticalwhen• the amount of data is large and• the same data is analysed repeatedly.In these situations input and output is preferablyaccomplished via data files. We have already describedin Section 9 the use of the commands saveand load that, respectively, write and read the valuesof variables to disk files.When data are written to or read from a file itis crucially important that a correct data formatis used. The data format is the key to interpretingthe contents of a file and must be known in order tocorrectly interpret the data in an input file. Thereare two types of data files: formatted and unformatted.Formatted data files uses format stringsto define exactly how and in what positions of arecord the data is stored. Unformatted storage, onthe other hand, only specifies the number format.The files used in this section are available from theweb sitehttp://www.maths.dundee.ac.uk/software/matlab.shtmlThose that are unformatted are in a satisfactoryform for the Windows version on Matlab (version6.1) but not on Version 5.3 under Unix.Exercise 24.1 Suppose the numeric data is storedin a file ’table.dat’ in the form of a table, asshown below.38


100 2256200 4564300 3653400 6798500 6432The three commands,>> fid = fopen(’table.dat’,’r’);>> a = fscanf(fid,’%3d%4d’);>> fclose(fid);respectively1. open a file for reading (this is designated bythe string ’r’). The variable fid is assignedauniqueintegerwhichidentifiesthefileused(a file identifier). We use this number in allsubsequent references to the file.2. read pairs of numbers from the file whoseidentifier is fid, onewith3digitsandonewith 4 digits, and3. close the file with file identifier fid.This produces a column vector a with elements,100 2256 200 4564 ...500 6432. Thisvectorcanbe converted to 5 ⇥ 2 matrix by the commandA = reshape(a,2,5)’;.A set of commands reading time-sound pressuredata from ’sound.dat’ is,Step 1: Assign a namestring to a file identifier.>> fid1 = fopen(’sound.dat’,’r’);The string ’r’ indicates that data is to be read(not written) from the file.Step 2: Read the data to a vector named ’data’ andclose the file,>> data = fscanf(fid1, ’%f %f’);>> fclose(fid1);Step 3: Partition the data in separate time and soundpressure vectors,>> t = data(1:2:length(data));>> press = data(2:2:length(data));The pressure signal can be plotted in a lin-lindiagram,>> plot(t, press);The result is shown in Figure 12.24.1 Formatted FilesSome computer codes and measurement instrumentsproduce results in formatted data files. In order toread these results into Matlab for further analysisthe data format of the files must be known. Formattedfiles in ASCII format are written to andread from with the commands fprintf and fscanf.fprintf(fid, ’format’, variables) writesvariables an a format specified in string ’format’to the file with identifier fida = fscanf(fid, ’format’,size) assigns tovariable a data read from file with identifierfid under format ’format’.Exercise 24.2 Study the available information andhelp on fscanf and fprintf commands. What isthe meaning of the format string, ’%3d\n’?Example 24.1 Suppose a sound pressure measurementsystem produces a record with 512 time – pressurereadings stored on a file ’sound.dat’. Eachreading is listed on a separate line according to adata format specified by the string, ’%8.6f %8.6f’.Fig. 12: Graph of “sound data” from Example24.124.2 Unformatted FilesUnformatted or binary data files are used whensmall-sized files are required. In order to interpretan unformatted data file the data precision mustbe specified. The precision is specified as a string,e.g., ’float32’, controlling the number of bits readfor each value and the interpretation of those bitsas character, integer or floating point values. Precision’float32’, for instance, specifies each valuein the data to be stored as a floating point numberin 32 memory bits.39


Example 24.2 Suppose a system for vibration measurementknowledge of Matlab. They also provides meansstores measured acceleration values as float-for e cient data management.ing point numbers using 32 memory bits. The datais stored on file ’vib.dat. Thefollowingcommandsillustrate how the data may be read into Matlab forA graphic user interface is a Matlab script file customizedfor repeated analysis of a specific type ofproblem. There are two ways to design a graphicanalysis.user interface. The simplest method is to use aStep 1: Assign a file identifier, fid, to the string specifyingthe file name.>> fid = fopen(’vib.dat’,’rb’);The string ’rb’ specifies that binary numbersare to be read from the file.Step 2 Read all data stored on file ’vib.dat’ intoavector vib.>> vib = fread(fid, ’float32’);>> fclose(fid);>> size(vib)ans =131072The size(vib) command determines the size,i.e., the number of rows and columns of thevibration data vector.In order to plot the vibration signal with acorrect time scale, the sampling frequency(the number of instrument readings takenper second) used by the measurement systemmust be known. In this case it is known tobe 24000 Hz so that there is a time intervalof 1/24000 seconds between two samples.Step 3: Create a column vector containing the correcttime scale.>> dt = 1/24000;>> t = dt*(1:length(vib))’;Step 4: Plot the vibration signal in a lin-lin diagram>> plot(t,vib);>> title(’Vibration signal’);>> xlabel(’Time,[s]’);>> ylabel(’Acceleration, [m/s^2]’);tool especially designed for the purpose. Matlabprovides such a tool and it is invoked by typing’guide’ at the Matlab prompt. Maximum flexibilityand control over the programming is, however, obtainedby using the basic user interface commands.The following text demonstrates the use of somebasic commands.Example 25.1 Suppose a sound pressure spectrumis to be plotted in a graph. There are four alternativeplot formats; lin-lin, lin-log, log-lin and log-log.The graphic user interface below reads the pressuredata stored on a binary file selected by the user,plots it in a lin-lin format as a function of frequencyand lets the user switch between the four plot formats.We use two m–files. The first (specplot.m) isthemain driver file which builds the graphics window.It calls the second file (firstplot.m) which allowsthe user to select among the possible *.bin files inthe current directory.% File: specplot.m%% GUI for plotting a user selected frequency spectrum% in four alternative plot formats, lin-lin,% lin-log, log-lin and log-log.%% Author: U Carlsson, 2001-08-22% Create figure window for graphsfigWindow = figure(’Name’,’Plot alternatives’);% Create file input selection buttonfileinpBtn = uicontrol(’Style’,’pushbutton’,...’string’,’File’,’position’,[5,395,40,20],...’callback’,’[fdat,pdat] = firstplot;’);% Press ’File’ calls function ’firstplot’25 Graphic User InterfacesThe e ciency of programs that are used often andby several di↵erent people can be improved by simplifyingthe input and output data management.The use of Graphic User Interfaces (GUI), whichprovides facilities such as menus, pushbuttons, slidersetc, allow programs to be used without any% Create pushbuttons for switching between four% different plot formats. Set up the axis stings.X = ’Frequency, [Hz]’;Y = ’Pressure amplitude, [Pa]’;linlinBtn = uicontrol(’style’,’pushbutton’,...’string’,’lin-lin’,...’position’,[200,395,40,20],’callback’,...’plot(fdat,pdat);xlabel(X);ylabel(Y);’);linlogBtn = uicontrol(’style’,’pushbutton’,...40


’string’,’lin-log’,...’position’,[240,395,40,20],...’callback’,...’semilogy(fdat,pdat);xlabel(X);ylabel(Y);’);loglinBtn = uicontrol(’style’,’pushbutton’,...’string’,’log-lin’,...’position’,[280,395,40,20],...’callback’,...’semilogx(fdat,pdat);xlabel(X);ylabel(Y);’);loglogBtn = uicontrol(’style’,’pushbutton’,...’string’,’log-log’,...’position’,[320,395,40,20],...’callback’,...’loglog(fdat,pdat);xlabel(X);% Create exit pushbutton with red text.ylabel(Y);’);exitBtn = uicontrol(’Style’,’pushbutton’,...’string’,’EXIT’,’position’,[510,395,40,20],...’foregroundcolor’,[1 0 0],’callback’,’close;’); Fig. 13: Graph of “vibration data” from Example25.1% Script file: firstplot.m% Brings template for file selection. Reads% selected filename and path and plots% spectrum in a lin-lin diagram.% Output data are frequency and pressure% amplitude vectors: ’fdat’ and ’pdat’.% Author: U Carlsson, 2001-08-22Executing this GUI from the command line(>> specplot) brings the following screen.Example 25.1 illustrates how the ’callback’ propertyallows the programmer to define what actionsshould result when buttons are pushed etc. Theseactions may consist of single Matlab commands orcomplicated sequences of operations defined in varioussubroutines.function [fdat,pdat] = firstplot% Call Matlab function ’uigetfile’ that% brings file selction template.[filename,pathname] = uigetfile(’*.bin’,...’Select binary data-file:’);% Change directorycd(pathname);% Open file for reading binary floating% point numbers.fid = fopen(filename,’rb’);data = fread(fid,’float32’);% Close filefclose(fid);% Partition data vector in frequency and% pressure vectorspdat = data(2:2:length(data));fdat = data(1:2:length(data));% Plot pressure signal in a lin-lin diagramplot(fdat,pdat);% Define suitable axis labelsxlabel(’Frequency, [Hz]’);ylabel(’Pressure amplitude, [Pa]’);Exercise 25.1 Five di↵erent sound recordings arestored on binary data files, sound1.bin, sound2.bin,..., sound5.bin. Thestorageprecisionis’float32’and the sounds are recorded with sample frequency12000 Hz.Write a graphic user interface that, opens an interfacewindow and• lets the user select one of the five sounds,• plots the selected sound pressure signal as afunction 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.26 Command SummaryThe command>> helpwill give a list of categories for which help is available(e.g. matlab/general covers the topics listedin Table 3.41


Further information regarding the commands listedin this section may then be obtained by using:>> help topictry, for example,>> help helpabs Absolute valuesqrt Square root functionsign Signum functionconj Conjugate of a complex numberimag Imaginary part of a complexnumberreal Real part of a complex numberangle Phase angle of a complex numbercos Cosine function, radianssin Sine function, radianstan Tangent function, radianscosd Cosine function, degreessind Sine function, degreestand Tangent function, degreesexp Exponential functionlog Natural logarithmlog10 Logarithm base 10cosh Hyperbolic cosine functionsinh Hyperbolic sine functiontanh Hyperbolic tangent functionacos Inverse cosine, result in radiansacosd Inverse cosine, result in degreesacosh Inverse hyperbolic cosineasin Inverse sine, result in radiansasind Inverse sine, result in degreesasinh Inverse hyperbolic sineatan Inverse tan, result in radiansatand Inverse tan, result in degreesatan2 Two–argument form of inversetanatanh Inverse hyperbolic tanround Round to nearest integerfloor Round towards minus infinityfix Round towards zeroceil Round towards plus infinityrem Remainder after divisionTable 2: Elementary FunctionsManaging commands and functions.help On-line documentation.doc Load hypertext documentation.what Directory listing of M-, MATandMEX-files.type List M-file.lookfor Keyword search through theHELP entries.which Locate functions and files.demo 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 functionsfrom memory.size Size of matrix.length Length of vector.disp Display matrix or text.Working with files and the operating system.cd Change current working directory.dir Directory listing.delete Delete file.! Execute operating system command.unix Execute operating system command& return result.diary Save text of MATLAB session.Controlling the command window.cedit Set command line edit/recall facilityparameters.clc Clear command window.home Send cursor home.format Set output format.echo Echo commands inside scriptfiles.more Control paged output in commandwindow.Quitting from MATLAB.quit Terminate MATLAB.Table 3: General purpose commands.42


Matrix analysis.cond Matrix condition number.norm Matrix or vector norm.Graphics & plotting.rcond LINPACK reciprocal condition figure Create Figure (graph window).estimator.clf Clear current figure.rank Number of linearly independent close Close figure.rows or columns.subplot Create axes in tiled positions.det Determinant.axis Control axis scaling and appearance.trace Sum of diagonal elements.null Null space.hold Hold current graph.orth Orthogonalization.figure Create figure window.rref Reduced row echelon form. text Create text.Linear equations.print Save graph to file.\ and / Linear equation solution; use plot Linear plot.“help slash”.loglog Log-log scale plot.chol Cholesky factorization.semilogx Semi-log scale plot.lu Factors from Gaussian elimination.semilogy Semi-log scale plot.Specialized X-Y graphs.inv Matrix inverse.polar Polar coordinate plot.qr Orthogonal- triangular decomposition.stem Discrete sequence or ”stem” plot.bar Bar graph.qrdelete Delete a column from the QR factorization.errorbar Error bar plot.stairs Stairstep plot.qrinsert Insert a column in the QR factorization.rose Angle histogram plot.hist Histogram plot.nnls Non–negative least- squares. compass Compass plot.pinv Pseudoinverse.feather Feather plot.lscov Least squares in the presence of fplot Plot function.known covariance.comet Comet-like trajectory.Eigenvalues and singular values.Graph annotation.eig Eigenvalues and eigenvectors. title Graph title.poly Characteristic polynomial. xlabel X-axis label.polyeig Polynomial eigenvalue problem. ylabel Y-axis label.hess Hessenberg form.text Text annotation.qz Generalized eigenvalues.gtext Mouse placement of text.rsf2csf Real block diagonal form to complexdiagonal form.contour Contour plot.grid Grid lines.cdf2rdf Complex diagonal form to real mesh 3-D mesh surface.block diagonal form.surf 3-D shaded surface.schur Schur decomposition.waterfall Waterfall plot.balance Diagonal scaling to improve view 3-D graph viewpoint specification.eigenvalue accuracy.svd Singular value decomposition. zlabel Z-axis label for 3-D plots.Matrix functions.gtext Mouse placement of text.expm Matrix exponential.grid Grid lines.expm1 M- file implementation of expm.expm2 Matrix exponential via Taylor series.Table 5: Graphics & plot commands.expm3 Matrix exponential via eigenvaluesand eigenvectors.logm Matrix logarithm.sqrtm Matrix square root.43funm Evaluate general matrix function.Table 4: Matrix functions—numerical linear algebra.


Index=, 28, 30%, 7,33’, 6.’, 7.*, 9..., 15,26./, 10.^, 11:, 5,6,18,21;, 4abs, 42acceleratorskeyboard, 8acosd, 9and, 29angle, 42ans, 3array, 17axes, 16, 17axis, 16auto, 16normal, 16square, 16ceil, 42clear, 34clf, 13close, 13colon notation, 5, 21column vectors, 6comment (%), 7, 33complexconjugate transpose, 6numbers, 4, 6complex numbers, 4components of a vector, 5conj, 42contour, 37cos, 42cosd, 42cosd, 9CPU, 28cumsum, 28cursor keys, 8diag, 19diary, 7dice, 35divideelementwise, 10doc, 2echo, 8elementary functions, 4elementwisedivide ./, 10power .^, 11product .*, 9,21end, 6,20error, 35eye, 19ezplot, 12false, 28Fibonnaci, 27, 35figure, 13filefunction, 33script, 7find, 32fix, 42fliplr, 23flipud, 23floor, 42floor, 35for loops, 27format, 3compact, 10long, 11rat, 10fraction, 10full, 23function m–files, 33functionselementary, 4trigonometric, 4get, 14graphs, see plottinggrid, 12,17,37GUI, 40hard copy, 13help, 2,34hold, 13,17if statement, 3044


imag, 42inner product, 8, 21, 22int2str, 27keyboard accelerators, 8labels for plots, 12legend, 13length, 6length of a vector, 5, 6, 8line styles, 12linspace, 12logical conditions, 28lookfor, 2loops, 27while, 29m–files, 7, 33matrix, 17building, 20diagonal, 19identity, 19indexing, 20orthogonal, 32size, 18sparse, 23special, 18spy, 20square, 19symmetric, 19tridiagonal, 23zeros, 18matrix products, 22matrix–vector products, 21max, 32,37mesh, 37meshgrid, 37min, 32,37multi–plots, 13nargin, 34norm of a vector, 9not, 28–30num2str, 27numbers, 3complex, 4format, 3random, 32rounding, 31ones, 18or, 29plotting, 12, 17, 36labels, 12line styles, 12printing, 13surfaces, 36title, 12powerelementwise, 11printing plots, 13prioritiesin arithmetic, 3productelementwise, 9, 21inner, 21, 22Pythagoras’s theorem, 34quit, 2rand, 32random numbers, 32real, 42rem, 42reshape, 18,39round, 42rounding error, 4rounding numbers, 31save, 7script files, 7semi–colon, 4, 17set, 15shapes, 13sign, 42sin, 42sind, 42size, 18sort, 5sparse, 23spdiags, 23spy, 20sqrt, 42str2num, 26strings, 12subplot, 14subscripts, 16sum, 27,31superscripts, 16timing, 28title for plots, 12toc, 28transposing, 6tridiagonal, 23trigonometric functions, 4true, 2845


type (list contents of m-file), 8variable names, 3vectorcolumn, 6components, 5row, 5what, 8while loops, 29whos, 7xlabel, 12,37ylabel, 12zeros, 18zoom, 1446

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!