New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Reuben Hudson DDS
Reuben Hudson DDS
GPA 3.55

Panayotis Kevrekidis

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Panayotis Kevrekidis
Class Notes
25 ?




Popular in Course

Popular in Mathematics (M)

This 18 page Class Notes was uploaded by Reuben Hudson DDS on Friday October 30, 2015. The Class Notes belongs to MATH 697 at University of Massachusetts taught by Panayotis Kevrekidis in Fall. Since its upload, it has received 9 views. For similar materials see /class/232216/math-697-university-of-massachusetts in Mathematics (M) at University of Massachusetts.

Similar to MATH 697 at UMass


Reviews for ST


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/30/15
MATLAB Basics MATLAB numbers and numeric formats All numerical variables are stored in MATLAB in double precision oatingpoint form In fact it is possible to force some variables to be of other types but not easily and this ability is not needed here F loating point representation of numbers is essentially equivalent to the scienti c notation of your calculator Speci cally a real number x is stored in binary oating point form as x ifgtilt 2E where f is called the mantissa and E the exponent The exponent is an integer positive or negative and the mantissa lies in the range 1 S f lt 2 This representation is entirely internal to the machine and its details are not important here They are important when analyzing carefully the performance of numerical algorithms Similar formats using the conventional decimal system are available for MATLAB input and output These formats can be set in the File 7 Preferences menu in the MATLAB command window They can also be changed using MATLAB commands format short format long pi ans 314159265358979 format short e 31 41 6e000 100pi ans 31 41 6e002 What does this e mean The result 31416e000 just means 31416 x 100 where three digits are allowed for the decimal exponent Similarly the final answer 31416e002 means 31416 gtlt102 or approximately 314 16 In the same way 31416e 002 means 31416 gtlt10 2 or approximately 0031416 One final note on this rst MATLAB session clearly the constant 7 is known and is built into MATLAB to high accuracy with the name pi You should therefore avoid using pi as a variable name in your MATLAB sessions Strings and printing In more advanced applications such as symbolic computation string manipulation is a very important topic For our purposes however we shall only need very limited skills in handling strings initially One most important use might be to include Your Name and the Course as part of your MATLAB workspace in a simple and automatic way This is easily achieved by using strings and the MATLAB print function fprintf in a special le called startupm which will be executed automatically when you start MATLAB Strings can be de ned in MATLAB by simply enclosing the appropriate string of characters in single quotes such as gt s My Name results in the output 5 My Name More complicated strings can be printed using the MATLAB function fprintf This is essentially a C programming command which can be used to obtain a widerange of printing speci cations Very little of its detail is needed at this stage We use it here only to illustrate printing strings If you want more details on advanced printing full details are provided in your MATLAB manual The use of fprintf to print the Name and Course information is illustrated by gt fprintf My Name n Course n My Name Course gt where the n is the newline command The nal one is included to ensure that the next MATLAB prompt occurs at the beginning of the next line rather than immediately at the end of the printed string To make this appear automatically every time you start MATLAB simply create a le called startupm which has this one command in it To create this m le click the New m le icon in the MATLAB window Type the single line fprintf My Name n Course n and then save this le with the name startup By default MATLAB will save this in a folder called Work which is where you want it to be In older versions of MATLAB the default location 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 adequate Editing in the Command Window Although we have not yet done very much in the MATLAB Command Window it is worth summarizing some of the basic editing operations available there Most of the elementary editing operations are completely standard BaCkSpace and Delete work just as in any other Windowsbased program Home moves the cursor to the beginning of the current line End moves the cursor to the end of the current line gt and lt move the cursor one place right or left Ctrl gt and Ctrl lt move one word right or left CtrIC and CtrIV have their usual effect of copying and pasting There are some nonstandard editing shortcuts which are useful ESC deletes the whole of the current line CtrIK deletes from the cursor to the end of the current line The T and 1 keys have special roles t recalls the previous line repeatedly up to many lines so that earlier lines can be reproduced This is often useful when you want to correct errors and typos in earlier code without having to retype complicated instructions 7 or simply to repeat an operation 1 recalls the next line Obviously if the current line is the last one then there is no next line These two keys are especially important because of the fact that MATLAB is interactive and each line is executed as it is completed so that you cannot go back up the Workspace to correct an earlier mistake Arithmetic operations Arithmetic in MATLAB follows all the usual rules and uses the standard computer symbols for its arithmetic operation signs Thus we use Symbol Effect Addition Subtraction gtslt Multiplication Division A Power In our present context we shall consider these operations as scalar arithmetic operations which is to say that they operate on two numbers in the conventional manner MATLAB s arithmetic operations are actually much more powerful than this We shall see just a little of this extra power later The conventional algebraic order of precedence between the various operations applies That is expressions in parentheses take precedence over powers A which take precedence over multiplication and division which in turn take precedence over addition and subtraction We have in fact already seen examples of some of these operations Assignment of values 7 whether direct numerical input or the result of arithmetic 7 is achieved with the usual sign Therefore within MATLAB and other programming languages we can legitimately write equations which are mathematically impossible For example the assignment statement gt x x01 has the effect of incrementing the value of the variable X by 01 so that if the current value of X before this statement is executed is 12 then its value after this is executed is 13 Such actions are often referred to as overwriting the value of X with its new value Similarly the MATLAB commands gt H gt ii2 result in the output Note the use of the to suppress the output from the rst line here There are some arithmetic operations which require great care The order in which multiplication and division operations are speci ed is especially important What is the output from the following MATLAB commands a2 b3 04 abc Here the absence of any parentheses results in MATLAB executing the two operations which are of equal precedence from lefttoright so that C First a is divided by b and then C The result is multiplied by C The result is therefore ans 26667 Note here the default variable ans is used for any arithmetic operations where the result is not assigned to a named variable This arithmetic is equivalent to 0 or as a MATLAB command b abc Similarly abC yields the same result as or achieved with the MATLAB command abc Use parentheses to be sure AJAT LAB does what you intend MATLAB s mathematical functions All of the standard mathematical functions 7 often called the elementary functions 7 that you will meet in your Calculus courses are available in MATLAB using their usual mathematical names Many other functions 7 the special functions 7 are also included you will most likely come across some of these in later mathematics and more especially engineering courses The elementary functions are listed in your User s Guide This listing includes several functions which will not be familiar to you yet and several that we shall not deal with in this book The important functions for our purposes are L b0 which could alternatively be abs X Absolute value sqrt X Square root sin x Sine cos X Cosine tan X Tangent log X Natural logarithm eXp X Exponential function 2 atan X Inverse tangent or arctan asin X Inverse sine or arcsin acos X Inverse cosine or arccos cosh X Hyperbolic cosine sinh X Hyperbolic sine Note that the various trigonometric functions eXpect their argument to be in radian or pure number form 7 NOT in degrees which are an arti cial unit based on the ancient Babylonians belief that a year was 360 days long Forexample sinpi3 gives the output Shortly we shall see how to use these functions to generate both tables of their values and plots of their graphs Also we shall see how to define other functions either as strings in the MATLAB command window or more usefully as function mfiles which can be saved for repeated use Vectors and Matrices In MATLAB the word vector should 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 needs for now These can be used to represent physical vectors but are much more versatile than that as we shall see There are two basic kinds of MATLAB vectors Row and Column vectors As the names suggest a row vector stores its numbers in a long horizontal list such as l234 l23 1032l which is a row vector with 6 components A column vector stores its numbers in a vertical list such as l 2 34 123 103 21 which is a column vector with the same 6 components In mathematical notation these arrays are usually enclosed in brackets There are various convenient forms of these vectors for allocating values to them and accessing the values that are stored in them The most basic method of accessing or assigning individual components of a vector is based on using an index or subscript which indicates the position of the particular component in the list The MATLAB notation for this subscript is to enclose it in parentheses For assigning a complete vector in a single statement we can use the notation These two are illustrated for the above row vector in the following MATLAB session X12123348723 X 1 0000 20000 1 2300 34000 87000 23000 X2X12X3 X 1 0000 34600 1 2300 34000 87000 23000 The first command simply initializes the vector with the given components The second performs arithmetic to set the second component equal to the first plus twice the third Note that the full vector is output and that the other components are unchanged In entering values for a row vector spaces could be used in place of commas For the corresponding column vector simply replace the commas with semicolons C All MATLAB vectors have their index or subscript begin at 1 This is NOT something that the user can vary For most applications this causes little difficulty but there are times when we must take special precautions in MATLAB programming to account for this 0 To switch between column and row format for a MATLAB vector we use the transpose operation denoted by This is illustrated for the row vector above by XX39 X 1 0000 34600 1 2300 34000 87000 23000 To switch back to row form just use the transpose operator again MATLAB has several convenient ways of allocating values to a vector where these values t a simple pattern A matrix is simply a rectangular array of numbers or other objects Thus a matrix is a row of columns in which each entry is a column vector of the same length or a column of rows in which each entry is a row of teh same length The entries are indexed in a similar way to vectors A23 refers to the element in Row2 and Column3 Thus the elements of a 3 x 4 matrix are labeled in MATLAB as follows A11 A12 A13 A14 A21 A22 A23 A24 A31 A32 A33 A34 Mathematically this same array is usually written as an 6112 6113 6114 A 021 022 023 024 6131 6132 6133 6134 The same matrix is a row of columns A1 A2 A3 A4 or a column of rows A1 A2 A3 where in each case the denotes a quotwild cardquot meaning all entries The use of in MATLAB is more powerful than this suggests The next section explains MATLAB s notation more fully This notation can also be used within teh subscripts of a vector or matrix We shall see this in examples MATLAB s notation The colon has a very special and powerful role in MATLAB Basically it allows an easy way to specify a vector of equally spaced numbers There are two basic forms of the MATLAB notation 0 Two arguments separated by a as in V 2 I 4 generates a row vector with rst component 2 last one 4 and others spaced at unit intervals 0 Three arguments separated by two s has the effect of specifying the starting value spacing final value For example the MATLAB command v 1022 generates the row vector V 10 08 06 04 020002 04 06 081012141618 20 Remember the syntax is startistepistop Also the step can be negative There are no practical restrictions on the length of such a vector or therefore on the range or spacing which can be used Of course very long vectors may have two negative effects Computing times are likely to rise dramatically and Output may take up so much room in the Window that you have no way of fathoming it 7 or printing it in reasonable time 0 Don t forget the use of a semicolon to suppress output in the Command Window There is another very useful aspect of MATLAB s colon notation It can also be used to specify a range of subscripts for a particular operation We see this in the following example WV328 W 06000 04000 02000 0 02000 04000 Note that the index of w still starts at 1 so that for example W3 ans 02000 linspace and logspace MATLAB has two other commands for specifying vectors conveniently linspace is used to specify a vector with a given number of equallyspaced elements between speci ed start and nish points This needs some care with counting to get convenient spacing For example xinspace0110 results in the vector 0 01111 02222 03333 04444 05556 06667 07778 08889 10000 Using 10 points results in just 9 steps xinspace0111 gives the vector 0 01 02 03 04 05 06 07 08 09 10 logspace has a similar effect except that the points are spaced on a logarithmic scale Tables of function values We can use MATLAB s vectors to generate tables of function values For example xinspace0111 ysinx X y generates the output ans 0 0 01000 00998 02000 01987 03000 02955 04000 03894 05000 04794 06000 05646 07000 06442 08000 07174 09000 07833 10000 08415 Note the use of the transpose to convert the row vectors to columns and the separation of these two columns by a comma Note also that all the standard MATLAB functions are de ned to operate on vectors of inputs in an elementbyelement manner The following example illustrates the use of the notation and arithmetic within the argument of a function ysqrt23001 1 y 7 14142 15166 16125 17029 17889 18708 19494 20248 20976 21679 22361 Array arithmetic Array arithmetic allows us to perform the equivalent arithmetic operations on all the components of a vector In most circumstances the standard arithmetic symbols achieve what is wanted and expected However especially for multiplication division and powers involving MATLAB vectors or matrices a dot is needed in conjunction with the usual operation sign These various operations are best illustrated with some simple MATLAB examples For these examples we shall use the following data vectors a and b and scalar number C a1234 b5302 02 Since the vectors a and b have the same size they can be added or subtracted from one another They can be multiplied or divided by a scalar or a scalar can be added to each of their components These operations are achieved using the following commands which produce the output shown ab ans 25000 15000 0 10000 Mathematically the operation of division by a vector does not make sense To achieve the corresponding componentwise operation we use C a Similarly for powers we use Aas follows ca ans 20000 10000 06667 05000 aquotc squares of components of a ans 2 4 816 powers of 02 Similarly the mathematical operation a gtslt b is not de ned but we may wish to generate the vector whose components are the products of corresponding elements of a and b ab ans 02000 06667 Inf 20000 Note the warning created by the division by zero in the third element of the nal operation here String functions The simplest userde ned functions in MATLAB are created as strings in the command window If we may need to evaluate these for arrays of arguments remember to use the dot operations where necessary As an example evaluate the function 2x3 3x x l l x2 forx 003063 x0033 f 2xquot33x1xquot2 yevaf gtgt XZy ans 0 0 03000 07717 06000 08915 09000 00337 12000 19806 15000 53654 18000 103904 21000 173575 24000 265829 27000 383889 30000 531000 The only difficulty here is remembering that each time we form products quotients or powers of vectors the corresponding dot operation must be used However there is another major drawback to this simple approach Every time we wish to evaluate the function f we must ensure that the argument is stored in a variable called x This may be inconvenient if we have several functions and arguments within a computation For this reason function mfiles are a much superior way of creating and saving userdefined functions Function mfiles To create a new mfile click the New mfile icon in the MATLAB command window If the mfile is to be a function mfile the first word of the file is function we must also specify names for the function its input and output The last two of these are purely local variable names These mimic the mathematical idea of defining a function y x but then assigning for example 2 Z This is just a shorthand for temporarily setting x 2 evaluating the output y of the function and assigning this value to 2 Function mfiles work the same way To illustrate we again evaluate the function 7 3 3x x 2x 1 x2 for x 0 03 0 6 3 but this time using a function mfile The mfile could be function yfun1x y2xquot33x1xquot2 Then the commands v0033 fvfun1 v VfV generate the same table of output as before Note that this time the vector V is a column vector and consequently so is fV There is no need for any transpose operations in the output line MATLAB mfiles can be much more involved than this as you will see during your course but the principles are the same Script m les A script mfile is a MATLAB program It consists of the set of MATLAB instructions for performing a particular task It is run by simply typing its name in the MATLAB command window The startupm file created earlier is a script mfile As well as storing complete programs perhaps the best way to save work if you are in the middle of an assignment is to use a script mfile By copying the instructions you used into an mf11e and saving it with some appropriate name you can then recover to exactly the point at which you stopped work Further instructions can then be added in the command window or by editing the mflle to add the new instructions As a simple example of a script m le we could store the mflle containing the three lines v0033 fvfun1v V with the name EXtabem and then the command extabe will again produce the same table of function values as we generated above Again obviously script mflles can be much more complicated than this Plotting MATLAB has several methods for plotting 7 both in two and threedimensional settings We shall concentrate on just one of the twodimensional plotting functions the most powerful lot MATLAB s plot function has the ability to plot many types of linear twodimensional graphs from data which is stored in vectors or matrices The user has control over the data points to be used for a plot the line styles and colors and the markers for plotted points All of these variations are detailed under plot in the User s Guide In this section we simply illustrate some of them with examples Markers The markers used for points in plot may be any of point circle 0 cross gtlt plus star gtslt C If any of these markers is used the corresponding plot consists only of the discrete points Line Styles The linestyle can be a solid line as before or one of several broken lines These are particularly useful in distinguishing curves for monochrome printing These styles are denoted by solid line dotted line dashed line dashdot Colors The colors available for MATLAB plots are yellow y green 9 magenta m blue b cyan C white W red r black k The color choice may be combined with any of the line styles or markers The use of these is illustrated with the following commands First the data vectors x5015 ytwofunsx are used for our illustrations The le twofunsm is function ytwofunsx y111xquot2 y2x1xquot2 The matrix y has two columns the rst of which has the values of 1 l l x2 and the second x 2 Perhaps the simplest method of obtaining multiple plots on the same axes is to use the command hold on The effect of this is that the next plot will be added to the current plot window To cancel this in order to produce a new gure hold off can be used The command hold acts as a simple toggle switch between these two states To obtain a plot of just the rst of these functions we can use gtgt P10tXYi1 which produces a blue solid line graph like that below has the values of A 73 72 4 n 1 2 a A Blue solid line is the default rst graph generated by plot To change this we use syntax such as 39m which would be added to the command to force magenta plus signs to be plotted The command plotxyl k yields the same curve plotted as a dotted black line It is worth noting that these effects are reliable screen effects and are usually reliable for printing directly from MATLAB Sometimes when graphics such as these are copied into other documents the printer drivers will convert all line styles to solid lines To get the plots of both functions on the same axes 7 but with different linestyles 7 use a command such as gt p0txiyi1 y k yxyy112y g39 quoti which results in the first curve being plotted as a solid black line and the second as a dashed green line Note that the vector X is needed for both sets of data MATLAB program control We consider the various ways of controlling the ow of a piece of MATLAB code These include 0 for loops 7 which enable us to have an operation repeated a speci ed number of times This may be required in summing terms of a series or specifying the elements of a nonuniformly spaced vector such as the first terms of a sequence de ned recursively C While loops 7 which allow the number of times the loop operation is performed to be determined by the results This is often used in iterative processes such as obtaining approximations to the solution of an equation if else 7 which is used when different actions are to be taken depending on the value of some variable A simple example would be in obtaining the maximum of two quantities Often the else clause may not be needed when a command is to be performed only if some condition is satis ed while nothing is done if the condition is not satis ed The condition itself may be a compound condition based on more than one truefalse determination We shall see examples of all these for loops The simplest for loops in MATLAB are of the form for varstart finish rstcommand astcommand end where start and nish are integers usually with start lt nish If nish lt start the loop is said to be empty and none of the commands will be performed Each of the commands in the loop will be performed once for each value of var beginning with the start value and increasing by 1 each time until the commands are executed for the last time with varfinish As a simple example the following commands generate the sum 223 29 2310 The terms are generated recursively 7 each is just onethird of its predecessor term2 82 for k1 10 termterm3 SSterm end S s 299998306491219 Note that both term and sum must be initialized before the loop for loops can be nested For example if we wished to repeat the summation for common ratios other than 3 we might use the following loops for n25 term2 Sn2 for k1 10 termtermn SnSnterm end d 25 S25 s 2 399805 3 299998 4 266667 5 250000 for loops can use a step other than 1 The general format is for counterstartstepstop en an end 39 while loops For many situations a loop is required but we don t know in advance how many times its commands will need to be performed One situation where this arises regularly is in obtaining repeated approximations to a quantity where we seek to achieve some speci ed accuracy in the nal result For example if we set x l and then repeat the instruction xcosx we will see that the values begin to settle down Suppose we wish to compute these until they agree to within 4 decimal places To achieve this we can use a While loop which is controlled not by a simple counter but by a logical condition The loop x11x00 while absx1x0gt1e4 x0x1 x1cosx0 end yields the nal result X1 07391 Note that we need two values in order to make the comparison Therefore two initial values must be speci ed and we must update them each time through the loop Again While loops can be nested While loops may contain for loops and vice versa The control of While loops can be more complicated than here It can contain compound logical conditions Logical and relational operators There are three basic logical operators which are important in MATLAB programming amp AND l OR N NOT The meanings of these should be fairly obvious Just remember that the mathematical meaning of OR is always inclusive The effects of these operators is simply summarized in the following truth table where T and F denote true and false respectively In MATLAB these values are actually represented numerically using 0 for false and l for true Strictly any nonzero equates to true so that some arithmetic can be done with logical values 7 if you are very careful There are other logical functions in MATLAB The details can be found in the User s Guide Generally you should use round the various components of compound logical conditions to be sure you have the precedence you intend For example AampBC and AampBC have very different meanings 7 just compare the two truth tables The relational operators which are often used in testing are mostly straightforward lt Less than gt Greater than lt Less than or equal to gt Greater than or equal to Equal to N Not equal to Note especially the double for logical testing of equality The single is only used in MATLAB for assignments if else Finally we introduce the basic structure of MATLAB s logical branching commands Frequently in programs we wish the computer to take different actions depending on the value of some variables Strictly these are logical variables or more commonly logical expressions similar to those we saw in de ning While loops There are three basic constructions all of which begin with if and nish with end The simplest has the form if condition commands end in which the statements in the commands block are only executed if the condition is satis ed true If the condition is not satis ed false then the commands block is skipped The second situation is if condition trueicommands else falseicommands end in which the rst set of instructions the trueicommands block are executed if condition is true while the second set the falseicommands block are executed if condition is false As a simple example the following code nds the maximum of two numbers if agt The third and most general form of branch is if rst condz39tz39on rst trueicommands elseif second condz39tz39on seconditrueicommands else second falseicommands end In this case the rst trueicommands block is executed if the rst condz tz on is true Otherwise in which case rst condz tz on is false a second condz tz on is tested if it is true the second trueicommands block is executed if this second condition is also false then the second falseicommands block is executed In fact if elseif elseif else end blocks can be nested arbitrarily deep Only the statements associated with the rst true condition will be executed The code below could be used to determine the nature of the roots of an arbitrary quadratic equation axz bx c 0 If 30 if b0 if 00 fprintf Every x is a solution n else else of 00 fprintf No solutions n end else else of b0 fprintf One solution n end elseif bquot2 4acgt0 else of a0 fprintf Two real solutions n elseif bquot2 4ac0 fprintf One repeated real solution n Ise fprintf Two complex solutions end


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


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'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Janice Dongeun University of Washington

"I used the money I made selling my notes & study guides to pay for spring break in Olympia, Washington...which was Sweet!"

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.