NUMERICAL ANALYSIS MATH 436
Popular in Course
Popular in Mathematics (M)
This 9 page Class Notes was uploaded by Angelina Steuber on Monday October 19, 2015. The Class Notes belongs to MATH 436 at Radford University taught by Staff in Fall. Since its upload, it has received 10 views. For similar materials see /class/224689/math-436-radford-university in Mathematics (M) at Radford University.
Reviews for NUMERICAL ANALYSIS
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 10/19/15
Math 436 Fall 2008 J Gerlach MATLAB NOTES These notes are intended as a quick introduction to MATLAB Mathworks the company behind MATLAB offers a Getting Started document This document can be opened by clicking on the question mark symbol on the MATLAB toolbar A pdf version is available on the Mathworks website at httpwwwmathworksco 39 39 J 39 beln pdf docMATLABgetstart ndf Page numbers used in these notes refer to the Getting Started document At RU you can get into MATLAB by going through the sequence Start gt Programs gt Radford University Course Software gt MathStatistics gt The Mathworks gt MATLAB I MATLAB is an interactive expression evaluator Algebraic operations work as usual with A for single variables But you need to be careful MATLAB assumes that all variables are matrices and you must make sure that the matrices have the correct dimension In addition the multiplication symbol is mandatory ie you need to write 3x The expression 3x is meaningless I Assign values to variables using Example a 4 5 compared to maple s a 45 I Interrupt a computation with Control C 0 You can write a transcript of your MATLAB session to a text le with the di ary command This le can be read edited and printed but it cannot be executed ie you cannot run a MATLAB program with a diary le This is different from your experience with maple les which can be edited and executed But then these are not simple text les either 0 Important symbols Comments I The format command controls the display of MATLAB output Important options gtgt format compact suppresses extra line feeds gtgt format long gtgt format long e scientific notation exponents gtgt format long g mix of fixed and exponential gtgt format long eng engineering notation Any ofthe longs can be replaced by short Help and Documentation The help command explains how a MATLAB command works its syntax and limitations and so on Example gtgt help inv I With lookfor you can search for MATLAB functions containing certain keywords Example gtgt lookfor Fourier Built inVariables are pi I j eps realmin realmax Inf among others see p 213 Bookkeeping Commands cl e a r clears the memory I who lists all defined variables I whos same with more information I what lists the m files in the current directory I save saves all variables to a file I load loads saved variables into memory Entering Matrices A matrix is a rectangular array of numbers More specifically an m by n matrix is an array of m rows and n columns Enter matrices using brackets begin new lines using the ENTER key or a semicolon A vector is a l by n matrix row vector or an m by 1 matrix column vector This process is explained on p 24 Builtin functions can be used to create special matrices diag eye ones zeros rand linspace logspace magi c and many more You can use small matrices to build larger ones see p 216 Concatenation The section on subscripts p 27 shows how you can extract or reset a speci c value in a matrix The commands s i ze and l ength let retrieve information about a matrix or a vector Operations with matrices o and scalar multiplication work the usual way matrices have to be of the same size for addition subtraction and A are executed in the sense of matrix multiplication etc For element by element operations use or A See p 224 Matrix block operations are built in For example if A is a given 4 by 7 matrix A eye4 zeros57 rand54 generates a 9 by 11 matrix A host of matrix functions is available Some functions perform termbyterm operations for example cos A evaluates the cosine of each entry in A Other functions are strictly matrix operations using linear algebra techniques for example B in A The Colon Operator The colon has a wide variety of uses Try the following sequence in MATLAB gtgt 3 gtgt A magic4 gtgt A3 gtgt A2 gtgt A gtgt A3 2 4 1 gtgt A2 4 Reshaping ofa matrix can be done with transpose rot 9 0 fl ipud fl iprl and re s hape Graphing A basic graph can be generated with the plot command If x and y are vectors of the same length the command plot x y will plot the points xkyk in the plane and connect with line segments Example Graph the function fx xze39x for lltxlt4 gtgt x linspace l4100 create x Values gtgt y xA2exp x define the y Values gtgt plotxy The looks of such a graph can be improved with commands such as axi s grid l egend text titl e x1 abel or yl abel These commands are explained in the Getting Started manual You can also modify the looks of your graph interactively from the gure window Activate the plot tools last icon and experiment with the features If you want to display several functions in the same gure just list the data sets separately For example gtgt xlinspace02pi200 gtgt y sinx gtgt 2 cosx gtgt plotxyxzxyZ gtgt axis0 2pi 3 3 grid gtgt title39sine cosine and tangent39 will display a graph with sine cosine and the tangent in a common gure You can display several graphs on a single page plot using the subplot command This might save you lots of paper Basically you de ne a matrix consisting of individual graphs with the subplot command Continuing the example above we could create four plots one each for sine cosine and tangent plus a common graph in this way gtgt subplot22l plotxyxzxyZ axis0 2pi 3 3 grid gtgt subplot222 plotxy axis0 2pi 3 3 grid gt subplot223 plotxz axis0 2pi 3 3 grid gtgt subplot224 plotxyZ axis0 2pi 3 3 grid V Three dimensional graphs visually display a matrix The row and the column indices represent the xycoordinates in the plane and the actual matrix entry gives the z coordinate For example try gtgt surfeye2025 or gtgt mesheye2025 If you want to plot a function fxy of two variables you need to rst create a matrix representing the x and y values as well as a matrix which represents the function This step can get a little tricky Let s do this by for an example Example Graph the function fxy l 7 xy on the rectangle l lxl2 gtgt x linspace ll20 x values gtgt y linspace l230 y Values gtgt XY mesngridxy matrices with coordinate information gtgt Z l XY define the function gtgt Now we display the function in several ways gt mesnXYZ gt surfXYZ gt contourXYZ gt imagescxyZ VVVV Depending on your artistic taste you might prefer surf over mesh or vice versa contour and images c may also prove useful for functions oftwo variables Again you can also experiment with the options in the gure window to improve the looks of your graph Programming Programming in MATLAB is done with socalled m les In order to run such a program the le has to be stored in the current directory or in a directory which is in the search path There are two types of m les script les and function les Script les contain a sequence commands as you would enter them in an interactive MATLAB session Within the MATLAB session you just type the name of the m le and the commands will be executed in the order given by the le Example Write an m le that will graph the function fX SiIIZX on the interval 0271 First we type the necessary commands into a le called s inedemo m This can easily be done with the MATLAB editor Our le could look like this 00 sine squared function l 0 Hl h linspace02pi300 sinx yA2 plotxy axis0 2pi O2 l2 grid title39fx SlHAZX39 Llt ltgtlt When in MATLAB just type s inedemo and the plot should appear Be careful using scripts since they may delete or overwrite existing data Function m les are the main programming tool Like any function in math they are used for inputoutput relations The rst line in a function m le must be of the form function output list functionnameinput list Here funct i onname should be identical with the name ofthe m le Input and output variables should be separated by commas All variables inside a function mflle are local variables they will not con ict with names in the calling program or the main MATLAB session The variables from the input list have assigned values already The value that was last assigned to an output variable will be communicated to the calling environment Example Assign to each angle 6 the matrix which represents a counterclockwise rotation by 6 degrees in the xyplane Note we are working in degrees and not with the radian measure The content ofthe le rot at i onmat rix m could look like this function A rotationmatrixt This function returns a 2x2 matrix corresponding to a rotation by t degrees o0 o0 Syntax A 7 rotationmatrixlttheta tpi180 convert degrees to radians A cost sint sint cost If this le is in the current directory we might do the following gtgt B60 rotationmatrix60 B60 05000 08660 08660 05000 gtgt help rotationmatrix This function returns a 2x2 matrix corresponding to a rotation by t degrees Syntax A rotationmatrixtheta It is possible to call functions from within functions The function which is being called must be on the current search path or it can be part of the mflle One function mf11e may contain many functions Input and Output This applies to script files and function files I The input command will prompt the user for input This can be very annoying when you run a program frequently and I would generally advise against using input prompts I The di sp command lets you display comments as strings or values of variables This is very useful when intermediate results are desired for example when you want to observe the progress of a routine or you try to debug an mflle fprint f can be used to format the output Example gtgt x 7 sqrt7 gtgt fprintf39 the square root of seven is 128fn39x the square root of seven is 264575131 Use n to start a new line The statement l 2 8 f indicates that you reserve 12 spaces for the output with 8 digits after the decimal point Use 0 f for oating points 0 e for scienti c notation o s for strings Flow Control First of all keep in mind that relational operators return a i if the relation is true else they return a 0 Example gtgt 3A 9 ans 1 gtgt 3A2 10 ans 0 if statements the i f has to be followed by a logical expression If its value is nonzero the next statements will be executed until an el s ei f an el s e or end is encountered If the value of the logical expression is zero the program will continue after the e l s e i f e l s e or the end statement 0 The simplest form is a single if For example gtgt if 4 x8 end 0 The general form of the i f statement is if expression statements elseif expression statements else statements end for loops In MATLAB s own words FOR Repeat statements a specific number of times The general form of a FOR statement is FOR variable expr statement statement END Example for k llO x lnk Y SCHUX end while hops Again let s look at MATLAB s definition WHILE Repeat statements an indefinite number of times The general form of a WHILE statement is WHILE expression statements END In a whi l e loop the number of repeats is not speci ed and it could be in nite if the programmer messes up Example factorial l k2 While factorial lt lOelO factorial kfactorial k kl end break andreturn A bre a k statement lets you jump out ofthe current loop fo r whi l e while with the return statement you stop the execution of the function routine and go back to the calling environment error This command works like return in that it stops the execution of the m le It also lets you display an error message Example if xlt0 error39please do not use negative numbers today39 end Other useful programming tools I nargin and nargout tests the number of input and output arguments This can be used to de ne defaults Example Make 0001 the default tolerance function y sowiesoxtol if nargin lt 2 tol 0001 end I f eval and calling functions within an mf11e This is best illustrated by an example function y sowiesofunxtol yl feva1funx tnis will evaluate the function pause This interrupts the execution of the program temporarily until a key is pressed or for a given amount of time 0 Keyboard Gives control to the command window until return is entered Vectorization and Preallocation Always precallocate space Don t just create matrices on the y or append to existing variables as needed Many loops can be avoided if you utilize MATLAB s vectorization environment Example The statements gtgt x zeros110 Preallocate memory gtgt for k 110 xk kAZ end mm gtgt x110 x x02 both generate a vector with the square numbers from 1 to 100 the second statement uses vectorization and is more ef cient Programming Advice A typical mf11e structure should have these parts 0 Prologue Contains instructions and information on how to use the le This is linked to the MATLAB help feature Process input data Check defaults verify that inputs are admissible Main Program
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'