### Create a StudySoup account

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

Already have a StudySoup account? Login here

# ST MATH 697

UMass

GPA 3.55

### View Full Document

## 9

## 0

## 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.

## Reviews for ST

### 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

NQP r kWNE HHH MHOQ MATLAB A TUTORIAL Creating vectors 2 Evaluating functions 3 f ac7 manipulating vectors 4 Plotting 5 Miscellaneous commands 7 Scripts 8 Saving your work 8 Timing your code 8 The for statement 9 The if statement 10 The while statement 12 MATLAB Functions 13 Matrix Operations 17 1 Creating Vectors and Matrices Row vectors there are many ways of creating a vector Explicit list gtgt x 0 1 2 3 4 5 7 What happens if you skip the semicolon gtgt x 012345 Inserting commas doesnt change anything Using aincren1entb gtgt x 0021 7 same as x0 02 04 06 08 gtgt x aAmb xaaAm a2Am a3Am b 7 that is vector from a to b in increments of size A1 7 What happens if A3 is not a integer divisor of b a Using linspacea7b7n gtgt x linspace016 7 vector containing 6 points on interval 01 gtgt a0b1n6 7 Set variables gtgt x linspaceabn 7 vector containing 11 points on interval ab 7 Note spacing is Am ln 1 Using for loops gtgt for i110 Z First example of a for loop Note 1101110 gtgt xii X What happens if you skip semicolon gtgt end gtgt a0b1n10 delxb an Z Set variables gtgt for i1n1 gtgt xiadelxi 1 Z index of x has to be an integer gt 0 gtgt end How long is the vector gtgt lengthx gtgt dsizex 7 What are the entries in the matrix d Column vectors Explicit list gtgt x01234 Transposng a row vector gtgt X O 1 2 3 4 Vectors are matrices A transposeA Matrices Explicit list gtgt A1 1 1 201 312 0 11 Special matrices gtgt Xzeros14 yzeros41 gtgt Xones14 yones41 2 Evaluating functions 3 f at manipulating vectors Example gtgt gtgt XOO11 ysinpix Z Type help elfun to see a list of predefined functions Alternative7 using a loop much slower gtgt gt gtgt gtgt gtgt V Vectors gtgt gtgt gtgt gtgt XOO11 nlengthX for i1n yisinpixi end are niatrices yXX X What happens Why X2OO21 yxx2 X What happens Why yx x X What is y yxx X What is y Componentwise operation gtgt yxx Z The dot denotes multiplication of components gtgt yx 3 Z The carat denotes exponentiation gtgt y2x Z Here you dont need a dot gtgt y1 X Z Here you do Accessing subvectors gtgt x0011 gtgt nlengthx gtgt X2X510 X What is X2 gtgt x2x13411 X What is x2 gtgt X2X2411 X What is X2 Accessing submatrices gtgt a100 90 85 117 110 108 84 84 84 96 90 88 gtgt mnsizex gtgt a2a23 X What is the matrix a2 gtgt a2a2 X What is a2 4 gtgt a2a2 X What is a2 gtgt a2a23 X What is a2 gtgt a2a2313 X What is a2 39Fhesun1c0nunandype7hehsunf gtgt y14210 sumy Z returns sum of all entries in vector y gtgt sumy124 Z what is it gtgt suma1 X with a as before what is it 3 Plotting l otconnnand gtgt XO11 y sin2pix gtgt plotxy Z the two vectors have to have same dimensions l xercise gtgt XO1 ysin2pix gtgt plotxy X What is going on Options Innetypen jons gtgt plotxy gtgt plotxy gtgt plotxy gtgt plotxy Cokn optkuw ymcrgbwk gtgt plotxy g Z green line line is default gtgt plotxy r h arkaoonns oxsdv ltgtph type help plot gtgt plotxy x Z blue star blue is default Using several options together gtgt plotxy r Z red line with star markers Plotting several curves gtgt XO0051 y1sin2pix y2cos2pix gtgt plotxy1xy2 gtgt plotxy1 b xy2 r gtgt XO0052 y1x y2xquot2 y3xquot3 y4xquot4 gtgt plotxy1 b xy2 r Xy3 g xy4 c Alternative7 using hold command gtgt x00051 y1sin2pix y2cos2pix gtgt plotxy1 b gtgt hold on gtgt plotxy2 r gtgt hold off Tluaaxm connnand gtgt axis0204 gtgt axis equal gtgt axis square Z Use help axis to see what other options there are Labe ing gtgt xlabel time t gt ylabel position st gt ylabel position st FontSize 16 gtgt title Its important to label your graphs gtgt text06 2 some text FontSize 16 gtgt setgca FontSize 16 gtgt legend x xquot2 VV Simplest Plots gtgt plotx Z Plots x vs its index quick way to see what is in x gtgt plotx1x2 Z Careful This does not plot x1 vs index gtgt Z and x2 vs index Instead plots x2 vx x1 gtgt plotx1x2x3 Z and this gives you an error Why 4D4Ece ane0usconnnands Comments gtgt Z This is a comment 39The hekgtandlook nconunands gtgt help zeros Z you need to know exact command name gtgt help for gtgt help Z lists topics for which there is help gtgt lookfor factorial X if you do not know the exact command name The print command gtgt print Z prints current figure to current printer gtgt print deps Z prints current figure to eps file gtgt print depsc Z prints current figure to color eps file gtgt print dps Z prints current figure to ps file T ua gunaconunand gtgt figure Z opens new figure gtgt figure2 Z makes figure 2 the current figure T uapauseconunand gtgt pause X What does this do gtgt pause2 X What does this do The continuation symbol gtgt x0 1 2 3 4 5 X To continue the current command gtgt 6 7 8 9 10 Z to the next line use The hold command see example in 3 Further example7 plot circle from y x l 27 a E 07 l VL P123 39The earconunand gtgt clear Z clears all variables from memory gtgt clear x y Z clears listed variables from memory 39The fconunand gtgt clf Z clears current figure 5 Scripts You can type a string of commands into a le whose name ends in m7 for example nmm7 If you then type gtgt flnm in your matlab window7 it executes all the commands in the le nmm Make sure you document your script les Add a few lines of comments that state what the script does 6 Saving your work Save all your script les on a oppy or CD RVV7 preferably organized in directories folders At the beginning of each in class programming session7 transfer all necessary les or directories from your oppy or from another UNM account using FsecureSSH onto the local working directory In DSH 1417 use E as your working directory In ESCP 1107 use Temp as your working directory 7 Timing your code the commands tictoc gtgt tic Z starts stopwatch gtgt statements gtgt toc Z reads stopwatch Exercise Find out how much faster the vector operation gtgt x00011 is than the following statement of componentwise operations gtgt for j1101 gtgt Xjj 1O01 gtgt end Answer using old version of matlab about 50 times faster gt MATLAB VEC39l 8 The for statement gtgt Z The command for repeats statements for a specific number of times gtgt Z The general form of the while statement is gtgt gtgt FOR variableexpr gtgt statements gtgt END gtgt gtgt Z expr is often of the form i0j0 or i0lj0 gtgt Z Negative steps 1 are allowed Example 1 What does this code do gtgt n 10 gtgt for i1n gtgt for j1n gtgt aij 1ij 1 gtgt end gtgt end 10 9 The if statement gtgt Z The general form of the if statement is gtgt gtgt IF expression gtgt statement gtgt ELSEIF expression gtgt statement gtgt ELSE expression gtgt statement gtgt END gtgt gtgt X where the ELSE and ELSEIF parts are optional gtgt Z The expression is usually of the form gtgt Z a oper b gtgt X where oper is equal lt gt lt gt or not equal Example 1 What does this code do gtgt n10 gtgt for i1n gtgt for j1n gtgt if i j gtgt Aij 2 gtgt elseif absij 1 gtgt Aij 1 gtgt else gtgt Aij 0 gtgt end gtgt end gtgt end Exercme 21e ne up douuisequence mk1 mk2 zrkis even 333k 1 if mk is odd 7 0 glven 39 Write a script that builds the up down sequence for k S 200 Plot the solution vector 36097 k l7 7 2007 for several initial conditions 11 gtgt gt gtgt gtgt gtgt V Z You can also combine two expressions X with the and or and not operations Z expression oper2 expression X where oper2 is amp and or not Example 3 What does this code do gtgt for i110 gtgt if i gt 5 amp remi20 gtgt xi1 gtgt else gtgt xi0 gtgt end gtgt end 12 10 The while statement gtgt gt gt gtgt gtgt gtgt gtgt gtgt VV Z The command while repeats statements an indefinite number of times X as long as a given expression is true Z The general form of the while statement is WHILE expression Example 1 What does this code do gtgtx4 gtgty1 gtgtn1 gtgt while nlt 10 gtgt y y xquotnfactorialn gtgt n n1 gtgt end Remember to initialize n and update its value in the loop Exercise 2 For the up dovvn sequence mkll ak2 if mk is even 333k 1 if mk is odd 7 0 glven 39 Write a script that builds the up dovvn sequence while y l and k S 2007 using the WHILE statement Plot the solution vector mUc7 k l7 7 2007 for several initial conditions 13 11 MATLAB Functions MATLAB Functions are similar to functions in Fortran or C They enable us to write the code more ef ciently7 and in a more readable manner The code for a MATLAB function must be placed in a separate m le having the same name as the function The general structure for the function is function Output parameters Name of Function Input Parametersgt quotA quotA Z Comments that completely specify the function quotA function body A function is called by typing gtgt variable Name of Function When writing a function7 the following rules must be followed 0 Somewhere in the function body the desired value must be assigned to the output variable 0 Comments that completely specify the function should be given immediately after the function statement The speci cation should describe the output and detail all input value assumptions 0 The lead block of comments after the function statement is displayed when the function is probed using help 0 All variables inside the function are local and are not part of the MATLAB workspace 14 Exercise 1 Write a function with input parameters a and n that evaluates the nth order Taylor approximation of 6 Write a script that calls the function for various values of n and plots the error in the approxima tion Solution The following code is written in a le called ApproxEXpm function yApproxExpxn Z Output parameter y nth order Taylor approximation of em Z Input parameters X scalar Z n integer sumo 1 for k1n sumo sumo Xquotkfactorialk end y sumo A script that references the above function and plots approximation error is X4 for n110 zn ApproxExpxn end exactexp4 plotabsexact z Exercise 2 Write the function ApproxEXp more ef ciently Exercise 3 Do the same as Exercises 1 and 27 but let X and y be vectors 15 Example 4 An example of a function that outputs more than one variable The functkuicornputesthe approxnnate demwathmaoffunctknifnarne7the error in the approximation7 and the estimated error The following code is written in a le called MyDerivm function derresterrMyDerivfnamedfnameahMeps Z Output parameter d approximate derivative using Z finite difference fhhfah Z err approximation error Z err estimated approximation error Z Input parameters fname name of function Z dfname name of derivative function Z a point at which derivative approx X h stepsize Z M upper bound on second derivative Z eps error in fahfa d fevalfnameahfevalfnameah err abs d feval dfname a esterr h2M2epsh A script that references the above function and plots the approximation error and the estimated error is a1 M1 eps10quot15 hlogspace 1 1616 nlengthh for i1n dierriesterriMyDeriv sin cos ahiMeps end loglogherr Exenjamp35VWhathappensifyoux l gtgt dMyDerivfnamedfnameahMeps orsnnpbr gtgt MyDerivfnamedfnameahMeps 7 16 Example 5 An example showing how to call a function Whose input is a user de ned function7 instead of a function implicitely de ned in MATLAB7 such as the 7sin7 function used in the previous example This MATLAB function in le MyPlotm plots the function fname on an interval from a to b using n points no output variables We then call it to plot 3 m2 on 07 2 using 100 points function MyPlotfnameabn Z Input parameters fname name of function Z ab endpoint of interval on Xaxis Z n number of points in ab x linspaceabn y fevalfnamex plot xy To call the above function type and the estimated error is MyPlot f1 O2100 Where fl is a user speci ed function That is7 you need to write the function that evaluates f1 at x in le f1m function yf1x 7 Input parameters fname name of function quot0 X vector 7 Output parameter y f X y X 2 17 12 Matrix operations lDe ningInatmces7anexanu e gtgt A 1 2 3 4 1 Special matrices gtgt eyen Z Matrix Multiplication gtgt CAB Z gtgt Z Inverses and determinants gtgt BinvA Z gtgt ddetA Z gtgt AB Z Solving systems gtgt Ab Z 2 3 1 1 1 1 1 X What does this do returns nxn identity matrix multiplies matrix A by matrix B provided dimensionally correct columns of A rows of B returns inverse of A returns determinant of A equals A inv B returns solution to Axb l8

### 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

#### "There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

#### "I made $350 in just two days after posting my first study guide."

#### "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."

#### "Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

### Refund Policy

#### STUDYSOUP CANCELLATION 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 support@studysoup.com

#### STUDYSOUP REFUND POLICY

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: support@studysoup.com

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 support@studysoup.com

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.