Transcription of MATLAB Basics - Calvin College
1 MATLAB BasicsMATLAB numbers and numeric formatsAllnumerical variables are stored in MATLAB indouble precision floating-pointform.(In fact it ispossibleto force some variables to be of other types but not easily and this abilityis not needed here.)Floating-pointrepresentation of numbers is essentially equivalent to the scientific notation of your calculator. Specifically a (real) numberxis stored inbinaryfloating point form asx f 2 Ewherefis called themantissaandEtheexponent. The exponent is an integer (positive ornegative) and the mantissa lies in the range 1 f 2. This representation is entirelyinternalto the machine and its details are not important here. (They are important when analyzingcarefully the performance of numerical algorithms.)Similar formats using the conventionaldecimalsystem are available for MATLAB inputand output. These formats can be set in theFile Preferences menu in the MATLAB command window. They can also be changed using MATLAB commands.
2 Format short pians format long pians format short e pians 000 100*pians 002 What does thisemean?The result 000 just means 100where threedigits are allowed for thedecimalexponent. Similarly the final answer 002 102or, approximately, In the same way, 002 means 10 2or, approximately, final note on this first MATLAB session: clearly the constant is known and is builtinto MATLAB to high accuracy with the namepi. You should therefore avoid usingpias avariable name in your MATLAB sessions!Strings and printingIn more advanced applications such as symbolic computation, string manipulation is a veryimportant topic. For our purposes, however, we shall only need very limited skills in handlingstrings initially. One most important use might be to include Your Name and the Course as partof your MATLAB workspace in a simple, and automatic, is easily achieved by using strings and the MATLAB print functionfprintfin a specialfile will be executed automatically when you start can be defined in MATLAB by simply enclosing the appropriate string ofcharacters in single quotes such as s My Name results in the outputs My NameMore complicated strings can be printed using the MATLAB functionfprintf.
3 This isessentially a C programming command which can be used to obtain a wide-range of printingspecifications. Very little of its detail is needed at this stage. We use it here only to illustrateprinting strings. If you want more details on advanced printing, full details are provided inyour MATLAB manual. The use offprintfto print the Name and Course information isillustrated by fprintf( My Name \n Course \n )My NameCourse where the\nis the new-line command. The final one is included to ensure that the nextMATLAB prompt occurs at the beginning of the next line rather than immediately at the endof the printed make this appear automatically every time you start MATLAB , simply create a has this one command in it. To create this m-file, click the Newm-file icon in the MATLAB window. Type the single linefprintf( My Name \n Course \n )and then save this file with the name startup . By default, MATLAB will save this in a foldercalled Work which is where you want it to be.
4 (In older versions of MATLAB , the defaultlocation may be different, but is still acceptable.)The function fprintf can be used for specifying the format of MATLAB s numeric output,too. However, for our purposes, the various default numerical formats are usually in the Command WindowAlthough we have not yet done very much in the MATLAB Command Window, it is worthsummarizing some of the basic editing operations available there. Most of the elementaryediting operations are completely standard:BackSpaceandDeletework just as in any other Windows-based program;Homemoves the cursor to the beginning of the current line;Endmoves the cursor to the end of the current line; and move the cursor one place right or left;Ctrl andCtrl move onewordright or their usual effect of copying and are some nonstandard editing shortcuts which are useful:Escdeletes the whole of the current line;Ctrl-Kdeletes from the cursor to the end of the current and keys have special roles: recalls the previous line (repeatedly up to many lines) so that earlier lines can bereproduced.
5 This is often useful when you want to correct errors and typos in earlier codewithout having to retype complicated instructions or simply to repeat an operation. recalls the next line. (Obviously if the current line is the last one, then there is no nextline.)These two keys are especially important because of the fact that MATLAB is interactiveand each line is executed as it is completed so that you cannot go back up the Workspace tocorrect an earlier operationsArithmetic in MATLAB follows all the usual rules and uses the standard computer symbolsfor its arithmetic operation we useSymbol Effect Addition Subtraction Multiplication/Division^PowerIn our present context we shall consider these operations asscalararithmetic operationswhich is to say that they operate on two numbers in the conventional manner. MATLAB sarithmetic operations are actually much more powerful than this. We shall see just a little ofthis extra power conventional algebraic order of precedence between the various operations is,expressions in parenthesestake precedence overpowers, ^which take precedence overmultiplication and division, ,/which, in turn, take precedence overaddition and subtraction, , We have in fact already seen examples of some of these values whether direct numerical input or the result of arithmetic isachieved with the usual sign.
6 Therefore, within MATLAB (and other programminglanguages) we can legitimately write equations which are mathematically impossible. Forexample, the assignment statement x x the effect of incrementing the value of the variablexby so that if the current value ofxbefore this statement is executed is then its value after this is executed is Such actionsare often referred to as overwriting the value ofxwith its new the MATLAB commands i 1; i i 2result in the outputi 3 Note the use of the ; to suppress the output from the first line are some arithmetic operations which require great care. The order in whichmultiplication and division operations are specified is especially is the output from the following MATLAB commands? a 2; b 3; c 4; a/b*cHere the absence of any parentheses results in MATLAB executing the two operations(which are ofequalprecedence) from left-to-right so that Firstais divided byb,and then Theresultis multiplied result is thereforeans here the default variable ansis used for any arithmetic operations where the resultis not assigned to a named arithmetic is equivalent toabcor as a MATLAB command (a/b)*cSimilarly,a/b/cyields the same result asa/bcorabcwhich could (alternatively) beachieved with the MATLAB command a/(b*c)Use parentheses to be sure MATLAB does what you intend!
7 MATLAB s mathematical functionsAll of the standard mathematical functions often called theelementaryfunctions thatyou will meet in your Calculus courses are available in MATLAB using their usualmathematical names. Many other functions thespecialfunctions are also included; youwill most likely come across some of these in later mathematics and, more especially,engineering elementary functions are listed in your User s Guide. This listing includes severalfunctions which will not be familiar to you yet, and several that we shall not deal with in thisbook. The important functions for our purposes are:abs (x)Absolute valuesqrt (x)Square rootsin (x)Sinecos (x)Cosinetan (x)Tangentlog (x)Natural logarithmexp (x)Exponential function,exatan (x)Inverse tangent, or arctanasin (x)Inverse sine, or arcsinacos (x)Inverse cosine, or arccoscosh (x)Hyperbolic cosinesinh (x)Hyperbolic sineNote that the various trigonometric functions expect their argument to be inradian(or purenumber) form NOTin degrees which are an artificial unit based on the ancientBabylonians belief that a year was 360 days long!
8 Forexample, sin(pi/3)gives the outputans we shall see how to use these functions to generate both tables of their values andplots of their graphs. Also we shall see how to define other functions either as strings in theMATLAB command window, or more usefully, as function m-files which can be saved forrepeated and MatricesIn MATLAB the wordvectorshould really be interpreted simply as list of numbers .Strictly it could be a list of other objects than numbers but list of numbers will fit our needsfor now. Thesecanbe used to represent physical vectors but are much more versatile than thatas we shall are two basic kinds of MATLAB vectors:RowandColumnvectors. As the namessuggest, a row vector stores its numbers in a long horizontal list such as1,2, , , , is a row vector with 6 components. A column vector stores its numbers in a vertical listsuch is a column vector with (the same) 6 components. In mathematical notation these arraysare usually enclosed in brackets.
9 There are various convenient forms of these vectors, for allocating values to them, andaccessing the values that are stored in them. The most basic method of accessing or assigningindividual components of a vector is based on using anindex,orsubscript, which indicates theposition of the particular component in the MATLAB notation for this subscript is toenclose it in parentheses .For assigning a complete vector in a single statement, we can use the notation. Thesetwo are illustrated for the above row vector in the following MATLAB session: x [1,2, , , , ]x x(2) x(1) 2*x(3)x first command simply initializes the vector with the given components. The secondperforms arithmetic to set the second component equal to the first plus twice the third. Notethat the full vector is output, and that the other components are entering values for a row vector, spaces could be used in place of commas. For thecorresponding column vector simply replace the commas with semi-colons.
10 All MATLAB vectors have their index or subscript begin at isNOTsomething that the user can vary. For most applications this causes littledifficulty but there are times when we must take special precautions in MATLAB programming to account for this. To switch between column and row format for a MATLAB vector we use thetransposeoperation denoted by .This is illustrated for the row vector above by: x x x switch back to row form : just use the transpose operator has several convenient ways of allocating values to a vector where these valuesfit a simple simply a rectangular array of numbers (or other objects). Thus a matrix is a rowof columns in which each entry is a column vector of the same length, or a column of rows inwhich each entry is a row of teh same length. The entries are indexed in a similar way tovectors: A(2,3) refers to the element in Row2 and Column3. Thus the elements of a 3 4matrix are labeled in MATLAB as follows:A 1,1 A 1,2 A 1,3 A 1,4 A 2,1 A 2,2 A 2,3 A 2,4 A 3,1 A 3,2 A 3,3 A 3,4 Mathematically this same array is usually written asA a11a12a13a14a21a22a23a24a31a32a33a34 The same matrix is a row of columnsA :,1 ,A :,2 ,A :,3 ,A :,4 or a column of rows:A 1,: A 2,: A 3,: where in each case the : denotes a "wild card" meaning all entries.