Introduction of Matlab pdf

introduction to computing using matlab and also the introduction to matlab & simulink a project approach
LylaKnight Profile Pic
LylaKnight,France,Professional
Published Date:12-07-2017
Your Website URL(Optional)
Comment
An Introduction to Matlab Version 3.1 David F. Griths formerly of Department of Mathematics The University of Dundee Dundee DD1 4HN Scotland, UK With additional material by Ulf Carlsson Department of Vehicle Engineering KTH, Stockholm, Sweden Thanks to Dr Anil Bharath, Imperial College, Dr Chris Gordon, University of Christchurch, Prof. Dr. Markus Kottmann, HSR Hochschule fur  Technik, Switzerland for their contributions to this revised version. Copyright c 1996 by David F. Griths. Amended October, 1997, August 2001, September 2005, October 2012, March 2015. This introduction may be distributed provided that it is not be altered in any way and that its source is properly and completely speci ed.Contents 15 TwoDimensional Arrays 17 15.1 Size of a matrix . . . . . . . . . . 18 1 MATLAB 2 15.2 Transpose of a matrix . . . . . . 18 15.3 Special Matrices . . . . . . . . . 18 2 Starting Up 2 15.4 The Identity Matrix . . . . . . . 19 15.5 Diagonal Matrices . . . . . . . . 19 3 Matlab as a Calculator 3 15.6 Building Matrices . . . . . . . . . 20 15.7 Tabulating Functions . . . . . . . 20 4 Numbers & Formats 3 15.8 Extracting Parts of Matrices . . 20 15.9 Elementwise Products (.) . . . 21 5 Variables 3 15.10Matrixvector products . . . . . 21 5.1 Variable Names . . . . . . . . . . 3 15.11MatrixMatrix Products . . . . . 22 6 Suppressing output 4 15.12Sparse Matrices . . . . . . . . . . 23 7 BuiltIn Functions 4 16 Systems of Linear Equations 23 7.1 Trigonometric Functions . . . . . 4 16.1 Overdetermined systems . . . . . 24 7.2 Other Elementary Functions . . . 4 17 Characters, Strings and Text 26 8 Vectors 5 18 Loops 27 8.1 The Colon Notation . . . . . . . 5 8.2 Extracting Parts of Vectors . . . 6 19 Timing 28 8.3 Column Vectors . . . . . . . . . . 6 8.4 Transposing . . . . . . . . . . . . 6 20 Logicals 28 20.1 While Loops . . . . . . . . . . . . 29 9 Keeping a record 7 20.2 if...then...else...end . . . . 30 10 Script Files 7 21 Further Builtin Functions 31 21.1 Rounding Numbers . . . . . . . . 31 11 Keyboard Accelerators 8 21.2 The sum Function . . . . . . . . . 31 12 Arithmetic with Vectors 8 21.3 max & min . . . . . . . . . . . . . 32 12.1 Inner Product () . . . . . . . . . 8 21.4 Random Numbers . . . . . . . . 32 12.2 Elementwise Product (.) . . . . 9 21.5 find for vectors . . . . . . . . . . 32 12.3 Elementwise Division (./) . . . . 10 21.6 find for matrices . . . . . . . . . 32 12.4 Elementwise Powers (.) . . . . . 11 22 Function m les 33 13 Plotting Functions 12 23 Plotting Surfaces 37 13.1 PlottingTitles & Labels . . . . 12 13.2 Grids . . . . . . . . . . . . . . . . 12 24 Reading/Writing Data Files 38 13.3 Line Styles & Colours . . . . . . 12 24.1 Formatted Files . . . . . . . . . . 39 13.4 Multiplots . . . . . . . . . . . . 13 24.2 Unformatted Files . . . . . . . . 39 13.5 Hold . . . . . . . . . . . . . . . . 13 13.6 Hard Copy . . . . . . . . . . . . 13 25 Graphic User Interfaces 40 13.7 Subplot . . . . . . . . . . . . . . 14 13.8 Zooming . . . . . . . . . . . . . . 14 26 Command Summary 42 13.9 Figure Properties . . . . . . . . . 14 13.10Formatted text on Plots . . . . . 15 13.11Controlling Axes . . . . . . . . . 16 14 Elementwise Examples 17 11 MATLAB Type quit at any time to exit from Matlab. Extensive documentation is available, either via  Matlab is an interactive system for doing the command line by using the 'help topic' numerical computations. command (see below) or via the internet. We recommend starting with the command  A numerical analyst called Cleve Moler wrote the rst version of Matlab in the demo 1970s. It has since evolved into a success- ful commercial software package. (a link may also be provided on the top line of the command window). This brings up a  Matlab relieves you of a lot of the mun- separate window which gives access to a short dane tasks associated with solving prob- video entitled \Getting Started" that describes lems numerically. This allows you to spend the purpose of the various panes in the main more time thinking, and encourages you Matlab window. to experiment. Help is available from the command line prompt.  Matlab makes use of highly respected al- Type help help for \help" (which gives a brief gorithms and hence you can be con dent synopsis of the help system), help for a list of about your results. topics. The rst few lines of this read HELP topics: -  Powerful operations can be performed us- - ing just one or two commands. MatlabCode/matlab - (No table of contents file) matlab/general - General purpose commands.  You can build up your own set of func- matlab/ops - Operators and special ... tions for a particular application. matlab/lang - Programming language ... matlab/elmat - Elementary matrices and ...  Excellent graphics facilities are available, matlab/randfun - Random matrices and ... A and the pictures can be inserted into LT X E matlab/elfun - Elementary math functions. and Word documents. matlab/specfun - Specialized math functions. These notes provide only a brief glimpse of the (truncated lines are shown with . . . ). Then to power and exibility of the Matlab system. For obtain help on \Elementary math functions", a more comprehensive view we recommend the for instance, type book help elfun Matlab Guide 2nd ed. D.J. Higham & N.J. Higham Clicking on a key word, for example sin will SIAM Philadelphia, 2005, ISBN: provide further information together with a link 0-89871-578-4. to doc sin which provides the most extensive documentation on a keyword along with exam- ples of its use. 2 Starting Up Another useful facility is to use the Matlab can be used in a number of di erent lookfor keyword ways or modes; as an advanced calculator in the calculator mode, in a high level programming command, which searches the help les for the language mode and as a subroutine called from keyword. See Exercise 15.1 (page 22) for an a C-program. More information on the rst two example of its use. of these modes is provided by these notes. When used in calculator mode all Matlab com- mands are entered to the command line from the keyboard at the \command line prompt" indicated with ''. 2Command Example of Output 3 Matlab as a Calculator format short 31.4162(4decimal places) The basic arithmetic operators are + - / format short e 3.1416e+01 and these are used in conjunction with brackets: format long e 3.141592653589793e+01 ( ). The symbol is used to get exponents format short 31.4162(4decimal places) (powers): 24=16. format bank 31.42(2decimal places) You should type in the commands shown at the prompt: . The command 2 + 3/45 format compact ans = 5.7500 is also useful in that it suppresses blank lines in the output thus allowing more information to be displayed. Is this calculation2 + 3/(45) or2 + (3/4)5? Matlab works according to the priorities: 1. quantities in brackets, 5 Variables 2. powers 2 + 32)2 + 9 = 11, 3-24 ans = 3. /, working left to right (34/5=12/5), -13 ans5 4. + -, working left to right (3+4-5=7-5), ans = Thus, the earlier calculation was for2 + (3/4)5 -65 by priority 3. The result of the rst calculation is labelled \ans" by Matlab and is used in the second cal- 4 Numbers & Formats culation, where its value is changed. We can use our own names to store numbers: Matlab recognizes several di erent kinds of num- bers x = 3-24 x = Type Examples -13 Integer 1362;217897 y = x5 Real 1:234;10:76 y = p Complex 3:21 4:3i (i = 1) -65 Inf In nity (result of dividing by 0) so thatx has the value13 andy =65. These NaN Not a Number, 0=0 can be used in subsequent calculations. These are examples of assignment statements: val- The \e" notation is used for very large or very ues are assigned to variables. Each variable small numbers: must be assigned a value before it may be used 3 -1.3412e+03 =1:3412 10 =1341:2 on the right of an assignment statement. 1 -1.3412e-01 =1:3412 10 =0:13412 All computations in MATLAB are done in dou- 5.1 Variable Names ble precision, which means about 15 signi cant gures. How Matlab prints numbers is con- Legal names consist of any combination of let- trolled by the \format" command. Type help ters and digits, starting with a letter. These format for full list. are allowable: Should you wish to switch back to the default format then format will suce. NetCost, Left2Pay, x3, X3, z25c5 3These are not allowable: sin, cos, tan and their arguments should be in radians. Net-Cost, 2pay, %x, sign e.g. to work out the coordinates of a point on a circle of radius 5 centred at the origin and Use names that re ect the values they repre- o having an elevation 30 ==6 radians: sent. Special names: you should avoid using x = 5cos(pi/6), y = 5sin(pi/6) 52 eps (which has the value 2.2204e-16= 2 . x = The smallest number greater than 1 which can 4.3301 be represented in Matlab is 1 + eps.) y = pi = 3.14159... = . 2.5000 If you wish to do arithmetic with complex num- p To work in degrees, use sind, cosd and tand. bers,both i and j have the value 1 unless The inverse trig functions are calledasin, acos, you change them 1 atan (as opposed to the usual arcsin or sin i,j, i=3 etc.). The result is in radians. ans = 0 + 1.0000i ans = 0 + 1.0000i acos(x/5), asin(y/5) i = 3 ans = 0.5236 ans = 0.5236 See Section 8.4 for more on complex numbers. pi/6 ans = 0.5236 6 Suppressing output 7.2 Other Elementary Functions One often does not want to see the result of in- These include sqrt, exp, log, log10 termediate calculationsterminate the assign- ment statement or expression with semicolon x = 9; sqrt(x),exp(x),log(sqrt(x)),log10(x2+6) x=-13; y = 5x, z = x2+y ans = y = 3 -65 ans = z = 8.1031e+03 104 ans = 1.0986 the value of x is hidden. Note that we can ans = place several statements on one line, separated 1.9395 by commas or semicolons. exp(x) denotes the exponential function exp(x) = x Exercise 6.1 In each case nd the value of the e and the inverse function is log: expression in Matlab and explain precisely the format long e, exp(log(9)), log(exp(9)) order in which the calculation was performed. ans = 9.000000000000002e+00 i) -23+9 ii) 2/33 ans = 9 iii) 32/3 iv) 34-522-3 format short v) (2/325)(3-43)2 vi) 3(34-252-3) and we see a tiny rounding error in the rst calculation. log10 gives logs to the base 10. 7 BuiltIn Functions A more complete list of elementary functions is given in Table 2 on page 42. 7.1 Trigonometric Functions Those known to Matlab are 48 Vectors w = 1 2 3, z = 8 9 cd = 2z,-w, sort(cd) These come in two avours and we shall rst de- w = scribe row vectors: they are lists of numbers 1 2 3 separated by either commas or spaces. The z = number of entries is known as the \length" of 8 9 the vector and the entries are often referred to cd = as \elements" or \components" of the vector. 16 18 -1 -2 -3 The entries must be enclosed in square brack- ans = ets. -3 -2 -1 16 18 v = 1 3, sqrt(5) Notice the last command sort'ed the elements v = of cd into ascending order. 1.0000 3.0000 2.2361 We can also change or look at the value of par- length(v) ticular entries ans = w(2) = -2, w(3) 3 w = Spaces can be vitally important: 1 -2 3 ans = v2 = 3+ 4 5 3 v2 = 7 5 8.1 The Colon Notation v3 = 3 +4 5 v3 = This is a shortcut for producing row vectors: 3 4 5 1:4 We can do certain arithmetic operations with ans = vectors of the same length, such as v and v3 in 1 2 3 4 the previous section. 3:7 ans = v + v3 3 4 5 6 7 ans = 1:-1 4.0000 7.0000 7.2361 ans = v4 = 3v v4 = 3.0000 9.0000 6.7082 More generally a : b : c produces a vector of v5 = 2v -3v3 entries starting with the value a, incrementing v5 = by the value b until it gets to c (it will not -7.0000 -6.0000 -10.5279 produce a value beyond c). This is why 1:-1 v + v2 produced the empty vector . ??? Error using == + Matrix dimensions must agree. 0.32:0.1:0.6 ans = i.e. the error is due to v and v2 having di erent 0.3200 0.4200 0.5200 lengths. -1.4:-0.3:-2 A vector may be multiplied by a scalar (a num- ans = ber, see v4 above), or added/subtracted to an- -1.4000 -1.7000 -2.0000 other vector of the same length. The opera- tions are carried out elementwise. We can build row vectors from existing ones: 58.2 Extracting Parts of Vectors and does not distinguish between row and col- umn vectors (compare with size described in r5 = 1:2:6, -1:-2:-7 x15.1). The size might be needed to deter- r5 = mine the last element in a vector but this can 1 3 5 -1 -3 -5 -7 be found by using the reserved word end: To get the 3rd to 6th entries: c2(end), c2(end-1:end) r5(3:6) ans = ans = 5 5 -1 -3 -5 ans = 4 5 To get alternate entries: r5(1:2:7) 8.4 Transposing ans = We can convert a row vector into a column vec- 1 5 -3 -7 tor (and vice versa) by a process called trans- What does r5(6:-2:1) give? posing which is denoted by '. See help colon for a fuller description. w, w', c, c' w = 8.3 Column Vectors 1 -2 3 These have similar constructs to row vectors ans = except that entries are separated by ; or \new- 1 lines" -2 3 c = 1; 3; sqrt(5) ans = c = 1.0000 1.0000 3.0000 3.0000 2.2361 2.2361 ans = c2 = 3 1.0000 3.0000 2.2361 4 t = w + 2c' 5 t = c2 = 3.0000 4.0000 7.4721 3 T = 5w'-2c 4 T = 5 3.0000 c3 = 2c - 3c2 -16.0000 c3 = 10.5279 -7.0000 -6.0000 If x is a complex vector, then x' gives the com- -10.5279 plex conjugate transpose of x: so column vectors may be added or subtracted x = 1+3i, 2-2i provided that they have the same length. ans = The length of a vector (number of elements) 1.0000 + 3.0000i 2.0000 - 2.0000i can be determined by x' length(c) ans = ans = 3 1.0000 - 3.0000i length(r5) 2.0000 + 2.0000i ans = 7 6Note that the components of x were de ned and the computation can be resumed where you without a operator; this means of de ning left o . We do not advocate this procedure ex- complex numbers works even when the variable cept is special circumstances, but suggest mak- i already has a numeric value. To obtain the ing use of script les (see Section 10). plain transpose of a complex number use .' as A list of variables used in the current session in may be seen with x.' whos ans = They can also be seen in the \Workspace" pane 1.0000 + 3.0000i of the main window. See help whos and help 2.0000 - 2.0000i save. One must be aware at all times, as the next whos example shows: i=3; 1+2i, 3-i, 3-1i Name Size Elements Bytes Density Complex ans = ans 1 by 1 1 8 Full No 1.0000 + 2.0000i 0 3.0000 - 1.0000i v 1 by 3 3 24 Full No v1 1 by 2 2 16 Full No in which only the 2nd element has been in u- v2 1 by 2 2 16 Full No enced by the value of the variable i. Grand total 16 elements using 128 bytes 9 Keeping a record 10 Script Files Issuing the command Script les are ordinary ASCII (text) les that diary mysession contain Matlab commands. It is essential that will cause all subsequent text that appears on such les have names having an extension .m the screen to be saved to the le mysession (e.g., myfile.m) and, for this reason, they are located in the directory in which Matlab was commonly known as m- les. The commands in invoked. You may use any legal lename ex- this le may then be executed using cept the names on and off. The record may be myfile terminated by Note: the command does not include the le name extension .m. diary off Script les are created with the built-in editor (it is possible to change to your favourite edi- The le mysession may be edited with your tor in the Preferences window). Any text that favourite editor (the Matlab editor, emacs, or follows % on a line is ignored. This enables de- even Word) to remove any mistakes. scriptive comments to be included. It is possi- If you wish to quit Matlab midway through a ble, via a mouse menu, to highlight commands calculation so as to continue at a later stage: that appear in the \Command History" pane save thissession to create a script le. \Cut and Paste" can be used to copy individual commands from the will save the current values of all variables to a \Command History" pane into a script le. le calledthissession.mat. This le cannot be edited. When you next startup Matlab, Exercise 10.1 1. Type in the commands from type x8.4 into a le called exsub.m. Its con- tents might look like: load thissession 7% My first script file: exsub.m The following emacslike commands may also w, w', 1 2 3, 1 2 3' be used: t = w + 21 2 3' % Use w to compute T cntrl a move to start of line T = 5w'-21 2 3 cntrl e move to end of line cntrl f move forwards one character cntrl b move backwards one character 2. Check in the \Current Folder" pane of cntrl d delete character under the cursor the Matlab window (or use the command what, which lists the m- les in the cur- rent directory) to see that the le is in Once the command is in the required form, the correct area. press return. 3. Use the command type exsub to see the Exercise 11.1 Type in the commands contents of the le. x = -1:0.1:1; 4. Execute the le with the command exsub. plot(x,sin(pix),'w-') hold on It is only the output from the commands (and plot(x,cos(pix),'r-') not the commands themselves) that are dis- played on the screen. To see the commands in Now use the cursor keys with suitable editing to the command window prior to their execution: execute: echo on and echo off will turn echoing o . Compare x = -1:0.05:1; the e ect of plot(x,sin(2pix),'w-') echo on, exsub, echo off plot(x,cos(2pix),'r-.'), hold off with the results obtained earlier. Seex22 for the related topic of function les. 12 Arithmetic with Vectors 11 Keyboard Accelerators 12.1 Inner Product () We shall describe two ways in which a meaning One can recall previous Matlab commands in may be attributed to the product of two vec- the Command Window by using the" and tors. In both cases the vectors concerned must cursor keys. Repeatedly pressing" will review have the same length. the previous commands (most recent rst) and, The rst product is the standard inner product. if you want to re-execute the command, simply Suppose thatu andv are two vectors of length press the return key. n,u being a row vector andv a column vector: To recall the most recent command starting with p, say, type p at the prompt followed by 2 3 v 1 ". Similarly, typing pr followed by" will recall 6 7 v 2 the most recent command starting with pr. 6 7 u = u ;u ;:::;u ; v =6 7: 1 2 n . . Once a command has been recalled, it may be 4 5 . edited (changed). You can use and to v n move backwards and forwards through the line, characters may be inserted by typing at the cur- The inner product is de ned by multiplying the rent cursor position or deleted using the Del corresponding elements together and adding the key. This is most commonly used when long results to give a single number (inner). command lines have been mistyped or when n X you want to reexecute a command that is very uv = u v : i i similar to one used previously. i=1 82 3 20 sqrt(uu'), norm(u) 4 5 For example, ifu = 10;11; 12,v = 21 ans = 22 19.1050 19.1050 then n = 3 and where norm is a builtin Matlab function that uv = 1020+(11)(21)+12(22) = 167: accepts a vector as input and delivers a scalar as output. It can also be used to compute other We can perform this product in Matlab by norms: help norm. u = 10, -11, 12, v = 20; -21; -22 Exercise 12.1 The angle, , between two col- prod = uv % row times column vector umn vectors x and y is de ned by Suppose we also de ne a row vector w and a 0 column vector z by xy cos = : kxkkyk w = 2, 1, 3, z = 7; 6; 5 w = Use this formula to determine the cosine of the 2 1 3 angle between z = 0 0 7 x = 1; 2; 3 and y = 3; 2; 1: 6 Hence show that the angle is 44:4153degrees. 5 and we wish to form the inner products of u Hint: see cosd and acosd. with w and v with z. 12.2 Elementwise Product (.) uw ??? Error using == The second way of forming the product of two Inner matrix dimensions must agree. vectors of the same length is known as the Hadamard an error results because w is not a column vec- product. It is rarely used in the course of nor- tor. Recall from page 6 that transposing (with') mal mathematical calculations but is an invalu- turns column vectors into row vectors and vice able Matlab feature. It involves vectors of the versa. So, to form the inner product of two row same type. If u and v are two vectors of the vectors or two column vectors, same type (both row vectors or both column vectors), the mathematical de nition of this prod- uw' % u & w are row vectors uct, which we shall call the Hadamard prod- ans = uct, is the vector having the components 45 uu' % u is a row vector uv = u v ;u v ;:::;u v : 1 1 2 2 n n ans = 365 The result is a vector of the same length and v'z % v & z are column vectors type as u and v. Thus, we simply multiply the ans = corresponding elements of two vectors. Sum- -96 ming the entries in the resulting vector would give their inner product. The Euclidean length of a vector is an example For example, if u = 10;11; 12, and w = of the norm of a vector; it is denoted by the 2; 1; 3 then n = 3 and symbolkuk and de ned by v u:w = 10 2; (11) (1); 12 (3) u n X u t 2 = 20;11; 36 kuk = juj ; i i=1 In Matlab, the product is computed with the wheren is its dimension. This can be computed operator . and, using the vectors u, v, w, z in Matlab in one of two ways: de ned on page 9, 9 u.w Exercise 12.2 Enter the vectors ans = U = 6; 2; 4; V = 3;2; 3; 0; 20 -11 36 2 3 2 3 u.v' 3 3 6 7 6 7 ans = 4 2 6 7 6 7 W = ; Z = 4 5 4 5 200 231 -264 2 2 v.z 6 7 into Matlab. Which of the products ans = UV, VW, UV', VW', WZ', U.V 140 U'V, V'W, W'Z, U.W, W.Z, V.W -126 is legal? State whether the legal products are -110 row or column vectors and give the values of the legal results. Perhaps the most common use of the Hadamard product is in the evaluation of mathematical expressions so that they may be plotted. 12.3 Elementwise Division (./) Example 12.1 Tabulate the function In Matlab, the operator ./ is de ned to give y =x sinx for x = 0; 0:25;:::; 1. element by element division of one vector by anotherit is therefore only de ned for vectors The display is clearer with column vectors so of the same size and type. we rst de ne a vector of x-values: (see Trans- a = 1:5, b = 6:10, a./b posing:x8.4) a = x = (0:0.25:1)'; 1 2 3 4 5 To evaluatey we have to multiply each element b = of the vectorx by the corresponding element of 6 7 8 9 10 the vector sinx: ans = x sinx = x sinx 0.1667 0.2857 0.3750 0.4444 0.5000 0 0 = 0 If we change to format rat (short for rational) 0.2500 0.7071 = 0.1768 0.5000 1.0000 = 0.5000 format rat 0.7500 0.7071 = 0.5303 (1:5)./(6:10) 1.0000 0.0000 = 0.0000 ans = 1/6 2/7 3/8 4/9 1/2 format compact To carry this out in Matlab: the output is displayed in fractions. Note that y = x.sin(pix) y = a./a 0 ans = 0.1768 1 1 1 1 1 0.5000 c = -2:2, a./c 0.5303 c = 0.0000 -2 -1 0 1 2 Warning: Divide by zero Note: a) the use of pi, b) x and sin(pix) ans = are both column vectors (the sin function is -0.5000 -2.0000 Inf 4.0000 2.5000 applied to each element of the vector). Thus, the Hadamard product of these is also a column The previous calculation required division by vector. 0notice the Inf, denoting in nity, in the an- swer. 10 a.b -24, ans./c 12.4 Elementwise Powers (.) ans = The square of each element of a vector could be -18 -10 0 12 26 computed with the command u.u. However, a neater way is to use the . operator: Warning: Divide by zero ans = u = 10, 11, 12; u.2 9 10 NaN 12 13 ans = 100 121 144 Here we are warned about 0/0giving a NaN u.u (Not a Number). ans = Example 12.2 Estimate the limit 100 121 144 sinx ans.(1/2) lim : x0 x ans = 10 11 12 The idea is to observe the behaviour of the ra- sinx u.4 tio for a sequence of values of x that ap- x ans = proach zero. Suppose that we choose the se- 10000 14641 20736 quence de ned by the column vector v.2 x = 0.1; 0.01; 0.001; 0.0001 ans = then 400 sin(pix)./x 441 ans = 484 3.0902 u.w.(-2) 3.1411 ans = 3.1416 2.5000 -11.0000 1.3333 3.1416 Recall that powers (. in this case) are done which suggests that the values approach . To rst, before any other arithmetic operation. Frac- get a better impression, we subtract the value of tional and decimal powers are allowed.  from each entry in the output and, to display When the base is a scalar and the power is a more decimal places, we change the format vector we get format long ans -pi n = 0:4 ans = n = -0.05142270984032 0 1 2 3 4 -0.00051674577696 2.n -0.00000516771023 ans = -0.00000005167713 1 2 4 8 16 Can you explain the pattern revealed in these and, when both are vectors of the same dimen- numbers? sion, We also need to use ./ to compute a scalar divided by a vector: x = 1:3:15 x = 1/x 1 4 7 10 13 ??? Error using == / x.n Matrix dimensions must agree. ans = 1./x 1 4 49 1000 28561 ans = 10 100 1000 10000 so 1./x works, but 1/x does not. 1113 Plotting Functions In order to plot the graph of a function, y = sin 3x for 0  x  1, say, it is sampled at a suciently large number of points and the points (x;y) joined by straight lines. Suppose we take N + 1 sampling points equally spaced a distance h apart: N = 10; h = 1/N; x = 0:h:1; de nes the set of pointsx = 0;h; 2h;:::; 1h; 1 with h = 0:1. Alternately, we may use the Fig. 2: Graph of y = sin 3x for 0 x 1 command linspace: The general form of the using h = 0:01. command is linspace (a,b,n) which gener- ates n + 1 equispaced points between a and b, inclusive. So, in this case we would use the 13.1 PlottingTitles & Labels command To put a title and label the axes, we use x = linspace (0,1,11); title('Graph of y = sin(3pi x)') The corresponding y values are computed by xlabel('x axis') ylabel('y-axis') y = sin(3pix); The strings enclosed in single quotes, can be and nally, we can plot the points with A anything of our choosing. Some simple LT X E plot(x,y) commands are available for formatting mathe- matical expressions and Greek characterssee The result is shown in Fig. 1 below, where it is Section 13.10. clear that the value of N is too small. See also ezplot the \Easy to use function plot- ter". 13.2 Grids A dotted grid may be added by grid on and is removed with grid off. 13.3 Line Styles & Colours The default is to plot solid lines. A solid red line is produced by plot(x,y,'rx') Fig. 1: Graph of y = sin 3x for 0 x 1 using h = 0:1. The third argument is a string comprising char- acters that specify the colour (red), the line On changing the value of N to 100: style (dashed) and the symbol (x) to be drawn at each data point. The order in which they N = 100; h = 1/N; x = 0:h:1; appear is unimportant and any, or all, may be y = sin(3pix); plot(x,y) omitted. The options for colours, styles and we get the picture shown in Fig. 2. symbols include: 12Colours Line Styles/symbols y yellow . point m magenta o circle c cyan x x-mark r red + plus g green - solid b blue star w white : dotted k black -. dashdot dashed The number of available plot symbols is wider Fig. 3: Graph of y = sin 3x and y = cos 3x than shown in this table. Use help plot to for 0x 1 using h = 0:01. obtain a full list. See also help shapes. The commandclf clears the current gure while close(1) will close the graphics window la- 13.5 Hold belled \Figure 1". To open a new gure win- A call to plot clears the graphics window be- dow type figure or, to get a window labelled fore plotting the current graph. This is not con- \Figure 9", for instance, type figure (9). If venient if we wish to add further graphics to the \Figure 9" already exists, this command will gure at some later stage. To stop the window bring this window to the foreground and the being cleared: next plotting commands will be drawn on it. plot(x,y,'r-'), hold on 13.4 Multiplots plot(x,y,'gx'), hold off \hold on" holds the current picture; \hold off" Several graphs may be drawn on the same gure releases it (but does not clear the window, which as in can be done with clf). \hold" on its own tog- plot(x,y,'k-',x,cos(3pix),'g') gles the hold state. A descriptive legend may be included with 13.6 Hard Copy legend('Sin curve','Cos curve') To obtain a printed copy select Print from the which will give a list of linestyles, as they ap- File menu on the Figure toolbar. pear in the plot command, followed by the brief Alternatively one can save a gure to a le for description provided in the command. later printing (or editing). A number of for- For further information do help plot etc. mats is available (use help print to obtain a The result of the commands list). To save the current gure in \Encapsu- lated Color PostScript" format, issue the Mat- plot(x,y,'k-',x,cos(3pix),'g') lab command legend('Sin curve','Cos curve') title('Multi-plot') print -depsc fig1 xlabel('x axis'), ylabel('y axis') which will save a copy of the image in a le grid called fig1.eps. is shown in Fig. 3. The legend may be moved print -f4 -djpeg90 figb either manually by dragging it with the mouse will save gure 4 as a jpeg le figb.jpg at a or as described in help legend. quality level of 90. It should be borne in mind that, despite its name, the \print" command does not send the le to a printer. 1313.7 Subplot Clicking the right mouse button will zoom out by a factor of two. The graphics window may be split into anmn Holding down the left mouse button and drag- array of smaller windows into each of which we ging the mouse will cause a rectangle to be out- may plot one or more graphs. The windows lined. Releasing the button causes the contents are counted 1 to mn rowwise, starting from of the rectangle to ll the window. the top left. Both hold and grid work on the zoom off turns o the zoom capability. current subplot. Exercise 13.1 Draw graphs of the functions subplot(221), plot(x,y) xlabel('x'),ylabel('sin 3 pi x') y = cosx subplot(222), plot(x,cos(3pix)) y = x xlabel('x'),ylabel('cos 3 pi x') subplot(223), plot(x,sin(6pix)) for 0 x 2 on the same window. Use the xlabel('x'),ylabel('sin 6 pi x') zoom facility to determine the point of inter- subplot(224), plot(x,cos(6pix)) section of the two curves (and, hence, the root xlabel('x'),ylabel('cos 6 pi x') of x = cosx) to two signi cant gures. subplot(221) (or subplot(2,2,1)) speci es that the window should be split into a 2 2 13.9 Figure Properties array and we select the rst subwindow. All plot properties can be edited from the Fig- ure window by selecting the Edit and Tools menus from the toolbar. For instance, to change thelinewidth of a graph, click Edit and choose Figure Properties... from the menu. Click- ing on the required curve will display its at- tributes which can be readily modi ed. One of the shortcomings of editing the gure window in this way is the diculty of repro- ducing the results at a later date. The recom- mended alternative involves using commands that directly control the graphics properties. The current setting of any plot property can be determined by rst obtaining its \handle num- ber", which is simply a real number that we save to a named variable: 13.8 Zooming plt = plot (x,y.3,'ko') We often need to \zoom in" on some portion plt = of a plot in order to see more detail. Clicking 188.0194 on the \Zoom in" or \Zoom out" button on the and then using theget command. This lists the Figure window is simplest but one can also use settings for a number of properties that include the command get(plt) zoom Color: 0 0 0 Pointing the mouse to the relevant position on LineStyle: '' the plot and clicking the left mouse button will LineWidth: 1 zoom in by a factor of two. This may be re- Marker: 'o' peated to any desired level. MarkerSize: 6 XData: 1 2 3 14YData: 27 8 1 Example 13.1 Plot the rst 100 terms in the  n 1 ZData: 1x0 double sequencefy g given by y = 1 + and il- n n n lustrate how the sequence converges to the limit The colour is described by a rgb triple in which e = exp(1) = 2:7183:::: as n1. 0 0 0 denotes black and 1 1 1 denotes white. Properties can be changed with the set Exercises such as this that require a certain command, for example amount of experimentation are best carried out set(plt,'markersize',12) by saving the commands in a script le. The will change the size of the marker symbol 'o' contents of the le (which we calllatexplot.m) while are: set(plt,'linestyle',':','ydata',1 8 27) will change the lifestyle from dashed to dot- close all ted while also changing theycoordinates of the figure(1); data points. The commands set(0,'defaultaxesfontsize',12) set(0,'defaulttextfontsize',16) x = 0:.01:1; y=sin(3pix); set(0,'defaulttextinterpreter','latex') plot(x,y,'k-',x,cos(3pix),'g') N = 100; n = 1:N; legend('Sin curve','Cos curve') y = (1+1./n).n; title('Multi-plot ') subplot(2,1,1) xlabel('x axis'), ylabel('y axis') plot(n,y,'.','markersize',8) set(gca,'fontsize',16,... hold on 'ytick',-1:.5:1); axis(0 N,2 3) redraw Fig. 3 and the last line sets the font plot(0 N,1, 1exp(1),'') size to 16points and changes the tick-marks on text(40,2.4,'y_n = (1+1/n)n') they-axis to1;0:5; 0; 0:5; 1see Fig. 4. The text(10,2.8,'y = e') ... in the penultimate line tell Matlab that the xlabel('n'), ylabel('y_n') line is split and continues on the next line. The results are shown in the upper part of Fig. 5. Fig. 4: Repeat of Fig. 3 with a font size of 16points and amended tick marks on they-axis. Fig. 5: The output from Example 13.1 (top) and Example 13.2 (bottom). 13.10 Formatted text on Plots It is possible to typeset simple mathematical The salient features of these commands are A expressions (using LT X commands) in labels, E 1. The set commands in lines 34 increase legends, axes and text. We shall give two illus- the size of the default font size used for trations. 15the axis labels, legends, titles and text. 2. Greek characters ; ;:::;; are pro- Line 4 tells Matlab to interpret any strings duced by the strings '\alpha', '\beta', A contained within symbols as LT X com- . . . ,'\omega', '\Omega'. the integral sym- E R mands. bol: is produced by '\int'. 2. De ning a variableN = 100 makes it eas- 3. The thickness of the line used in the plot ier to experiment with a di erent number command is changed from its default value of sampling points. (0:5) to 2. 3. The size of the plot symbol \." is changed 4. The graphics are saved in jpeg format to from the default (6) to size 8 by the ad- the le eplot1. ditional string followed in the plot com- mand. 13.11 Controlling Axes 4. The axis command changes the dimen- The look of a graph can be changed by using sions of the plotting area to be 0xN the axis command. We have already seen in and 2y 3. Example 13.1 how the plotting area can be changed. The axis command has four parameters, axis equal is required in order that a circle the rst two are the minimum and max- does not appear as an ellipse imum values of x to use on the axis and the last two are the minimum and maxi- clf, N = 100; t = (0:N)2pi/N; mum values of y. x = cos(t); y = sin(t); plot(x,y,'-',0,0,'.'); 5. The command text(40,2.4,'string') set(gca,'ytick',-1:.5:1) prints string at the location with coordi- axis equal nates (40 2.4). See Fig. 6. We recommend looking at help 6. The string y_n gives subscripts: y , while n 3 axis and experimenting with the commands x3 gives superscripts: x . axis equal, axis off, axis square, Example 13.2 Draw a graph the functiony = axis normal, axis tight in any order. 2 3 3x e sin (3x) on the interval2x 2. The appropriate commands are included in the script le for the previous example (so the de- fault values continue to operate): subplot(2,1,2) x = -2:.01:2; y = exp(-3x.2).sin(8pix).3; plot(x,y,'r-','linewidth',1) xlabel('x'), ylabel('y') text(-1.95,.75,' \exp(-40x2)\sin3(8\pi x)') print -djpeg90 eplot1 The results are shown in the lower part of Fig. 5. 3 Fig. 6: Use of axis equal to get a circle to A 1. sin 8x is typeset by the LT X string E appear correctly. \sin3 8\pi x and translates into the Matlab command sin(8pix).3the position of the exponent is di erent. 1614 Elementwise Examples Exercise 14.1 Tabulate the functions 2 2 y = (x + 3) sinx Example 14.1 Draw graphs of the functions sinx 1 and i) y = ii) u = +x 2 x (x1) 2 2 1=3 2 z = sin x=(x + 3) (10x) 2 x +1 iii) v = iv) w = 2 2 1=2 x4 (4x ) forx = 0; 0:2;:::; 10. Hence, tabulate the func- for 0x 10. tion 2 2 2 (x + 3) sinx sin x w = : x = 0:0.1:10; 2 (x + 3) y = sin(x)./x; Plot a graph of w over the range 0x 10. subplot(221), plot(x,y), title('(i)') Warning: Divide by zero u = 1./(x-1).2 + x; 15 TwoDimensional Arrays subplot(222),plot(x,u), title('(ii)') Warning: Divide by zero A rectangular array of numbers havingm rows v = (x.2+1)./(x.2-4); and n columns is referred to as an mn ma- subplot(223),plot(x,v),title('(iii)') trix. It is usual in a mathematical setting to Warning: Divide by zero enclose such objects in either round or square bracketsMatlab insists on square ones. For w = ((10-x).(1/3)-1)./sqrt(4-x.2); example, when m = 2;n = 3 we have a 2 3 Warning: Divide by zero matrix such as subplot(224),plot(x,w),title('(iv)')   5 7 9 A = 1 3 7 To enter such an matrix into Matlab we type it in row by row using the same syntax as for vectors: A = 5 7 9 1 -3 -7 A = 5 7 9 1 -3 -7 Rows may be separated by semi-colons rather than a new line: B = -1 2 5; 9 0 5 B = Note the repeated use of the \dot" (element- -1 2 5 wise) operators. 9 0 5 Experiment by changing the axes (page 16), C = 0, 1; 3, -2; 4, 2 grids (page 12) and hold(page 13). C = 0 1 subplot(222),axis(0 10 0 10) 3 -2 grid 4 2 grid D = 1:5; 6:10; 11:2:20 hold on D = plot(x,v,''), hold off, 1 2 3 4 5 plot(x,y,':') 6 7 8 9 10 11 13 15 17 19 17So A and B are 2 3 matrices, C is 3 2 and D 1 9 is 3 5. 7 -7 In this context, a row vector is a 1n matrix also redistributes the elements of A columnwise. and a column vector a m 1 matrix. 15.2 Transpose of a matrix 15.1 Size of a matrix Transposing a vector changes it from a row to a We can get the size (dimensions) of a matrix column vector and vice versa (seex8.4)recall with the command size that is also performs the conjugate of complex size(A), size(x) numbers. The extension of this idea to matrices ans = is that transposing interchanges rows with the 2 3 corresponding columns: the 1st row becomes ans = the 1st column, and so on. 3 1 D, D' size(ans) D = ans = 1 2 3 4 5 1 2 6 7 8 9 10 So A is 2 3 and x is 3 1 (a column vector). 11 13 15 17 19 The last command size(ans) shows that the ans = value returned by size is itself a 1 2 matrix 1 6 11 (a row vector). We can save the results for use 2 7 13 in subsequent calculations. 3 8 15 4 9 17 r c = size(A'), S = size(A') 5 10 19 r = size(D), size(D') 3 ans = c = 3 5 2 ans = S = 5 3 3 2 Arrays can be reshaped. A simple example is: 15.3 Special Matrices Matlab provides a number of useful builtin A(:) matrices of any desired size. ans = ones(m,n) gives an mn matrix of 1's, 5 1 P = ones(2,3) 7 P = -3 1 1 1 9 1 1 1 -7 zeros(m,n) gives an mn matrix of 0's, which converts A into a column vector by stack- ing its columns on top of each other. This could Z = zeros(2,3), zeros(size(P')) also be achieved using reshape(A,6,1). The Z = command 0 0 0 0 0 0 reshape(A,3,2) ans = ans = 0 0 5 -3 180 0 Notice that multiplying the 3 1 vector x by 0 0 the 3 3 identity I has no e ect (it is like mul- tiplying a number by 1). The second command illustrates how we can construct a matrix based on the size of an ex- 15.5 Diagonal Matrices isting one. Try ones(size(D)). An nn matrix that has the same number A diagonal matrix is similar to the identity ma- of rows and columns and is called a square trix except that its diagonal entries are not nec- matrix. essarily equal to 1. A matrix is said to be symmetric if it is equal 2 3 3 0 0 to its transpose (i.e. it is unchanged by trans- 4 5 D = 0 4 0 position): 0 0 2 S = 2 -1 0; -1 2 -1; 0 -1 2, is a 3 3 diagonal matrix. To construct this in S = Matlab, we could either type it in directly 2 -1 0 D = -3 0 0; 0 4 0; 0 0 2 -1 2 -1 D = 0 -1 2 -3 0 0 St = S' 0 4 0 St = 0 0 2 2 -1 0 -1 2 -1 but this becomes impractical when the dimen- 0 -1 2 sion is large (e.g. a 100 100 diagonal matrix). S-St We then use the diag function.We rst de ne a ans = vector d, say, containing the values of the diag- 0 0 0 onal entries (in order) then diag(d) gives the 0 0 0 required matrix. 0 0 0 d = -3 4 2, D = diag(d) d = 15.4 The Identity Matrix -3 4 2 D = Thenn identity matrix is a matrix of zeros -3 0 0 except for having ones along its leading diag- 0 4 0 onal (top left to bottom right). This is called 0 0 2 eye(n) in Matlab (since mathematically it is usually denoted by I). On the other hand, if A is any matrix, the com- mand diag(A) extracts its diagonal entries: I = eye(3), x = 8; -4; 1, Ix I = F = 0 1 8 7; 3 -2 -4 2; 4 2 1 1 1 0 0 F = 0 1 0 0 1 8 7 0 0 1 3 -2 -4 2 x = 4 2 1 1 8 diag(F) -4 ans = 1 0 ans = -2 8 1 -4 Notice that the matrix does not have to be 1 square. 19