### Create a StudySoup account

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

Already have a StudySoup account? Login here

# Class Note for MATH 215 with Professor Dostert at UA

### View Full Document

## 16

## 0

## Popular in Course

## Popular in Department

This 4 page Class Notes was uploaded by an elite notetaker on Friday February 6, 2015. The Class Notes belongs to a course at University of Arizona taught by a professor in Fall. Since its upload, it has received 16 views.

## Reviews for Class Note for MATH 215 with Professor Dostert at UA

### 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: 02/06/15

An Introduction to Matlab Part 6 This lecture does not use all of the ideas from our previous lectures It is simply intended as a tutorial for those of you who would like to attempt to use Matlab for programming The nal result is a nice little Newtonquot Method for a speci c function f You should know how to create and execute functions and scripts and have a familiarity with vectors and component wise arithmetic I am also assuming you have ome familiarity ith programming in general This is not meant to be a tutorial on how to program but rather how to use Matlab to program This tutorial is also a bit more example oriented again since it is geared toward people who can program already So we are covering only 0 Programming in Matlab Programming in Matlab Most everything that one would expect to work in a programming language such as C Cw V or Fortran works in Matlab V ell work through some examples describing some differences between Matlab and other languages A huge advantage in Matlab is that we have access to a gigantic library of mathematical functions To access this many functions in other languages often requires the use of third party programs which can sometimes be a bit di icult to compile and use Writing working Matlab code tends to take much less time than in C or Cw but code tends to be slower Many people including elf use Matlab to con rm ideas or algorithms If you then need to have the algorithm do something very fast you program it in C or C VVVV w after con rming the algorithm works in Matlab 14 Data Typos First there are generally no data types in Matlab separating oats integers doubles unsigned integers or anything like that If I have a 1 and b 4 then a b will be 25 and not 0 like if these were both integers and I was in C Matlab is going to convert our variables to whatever it thinks we need and it s going to be fair about it Be aware of this fac ice you may need to use oor or ccil to get things as integers 24 H cllo World A nice way to start learning a programming language is to write a program which displays H cllo World a Open Matlabi If you already have it open type clcar all in the Command Windoixi Open up the Matlab editor This can be accomplished by typing cdit in the Command Window or by using the menus b We re going to create a script le so all we need to do is type the series of commands we want to have executed When you opened the editor you should have had an empty document open likely titled untitlchm Save this le wherever you want as H cllo Worldm by going to File gtSaveAs4 c Now we ll tvpe the command that displays Hcllo World4 It is called fprintf For those of your who know C the command is very familiar We type fprint Hcllo World2 n Here the text we wish to display is enclosed in single quotes and the n is a command character that tells fprintf to print a new linei d fprintf would also be the command you use to write out to a le If you ever need to do this consult the Matlab documentation 3 Loops Anyone who programs knows that you re going to have to eventually learn to use a loop to be effective a Let us create a new 4m le save it as myprogramm Once you have saved the le hit the run button in the editor You will likely have to click Cliangc Dircctory when prompted by Matlab we do this simply to make sure Matlab switches to the same directory as your program b 39W e going to make myprogram a function which takes two arguments 30 and N and returns the variable a We do this by typing the rst line of the function to be function a myprogram 10N c Next w re going to de ne a function f in Matlab One way to do this is to use what is called an inlinc function For you next line type f inlinc ar 2 23 8 An inline function will assume that I am de ning a function of z or z y if I use two variables So essentially this make f a function which takes I as an argument and returns y x2 7 2x 7 8 d 0 5 We re going to perform an iteration on f for N steps at a starting value of 104 The idea is that w re going to compute zn1 In 7 f over an over again starting at 1 and going to IN The function will print out each value of 14 To do a loop we use the function for The construct for for consists of a variable name and a vector The variable name tells the loop which variable is going to change and the vector is going to indicate how it will change In order to end a loop we type endl Eve r39thing that we want to be looped we put between the for and the end So for your program the next lines are 371 1390 for n 1N an 1 end 3170177700 Run this function from the Command Window 4 Try N 4 and some different values of I try at least I 720 and 4 To run for z 0 and N 3 we would type a myprogram 0 3 What happens for z 72 and z 4 Can you explain why this is so 44 ifthen if elsestatements Another crucial component to any programming is the if then statement a l C 1 We re going to use the same exact program as above but just modify a few lines We re going to implement Newton s method for fz 12 7 21 7 8 with a check that quits the loop if Newton s method has converged First in order to use Newton s method we have to de ne the derivative of f a After you de ne f but before the loop de ne fp to be an inline function that is the derivative of f Recall what ewton s method does We iterate In1 In 7 So re In anfarn with anv w1 arnfarn iarn Try rerunning the program with N 10 and z 73 Try it with z 10 You ll notice that long before we hit N 10 it appears w e reached the stable point of the iteration the root of the polynomial We want to tell the loop to quit if this is the case We re going to use an if then statement to do this The construct in Matlab actually uses if else39if else and end It would look like place your previous iteration a n r1 if someth39ing some statement here else39if someth39ing else some other statement here another statement here end For our program we want an if statement within the loop that quits if is small and continues otherwise Inside the loop and after the Newton iteration we put the statement ifabsfar7w1 1e6 rrint Ne39wtons Method converged in d iterations n n break end The break command quits the innermost for loop A return command instead of break would quit the entire function A eont39in39ae command would quit the current iteration of the loop and cycle to the next iteration ie quit at that point and index n Rerun your program with N 10 and try out many different values of 14 What happens 5 while loops We explore how to create a while loop which is useful when we do not know how many iterations it will take something to converge a We re going to modify the previous program You should have a section that looks a whole lot like for n 1N arnv w1 anfarnfpan ifdbsfarn1 1e6 wtons Method converged in d iterdtions EnCn Instead of creating a for loop we can use a while What do we really want We want this to keep running while dbsfan1 gt 1e6 If we hit the maximum number of iterations N then we ll quiti How can we do this n 1 whiledbsfarn gt 1e6 arnv w1 anfarnfpan ifn N fprintf rewtons Method did not converge in d iterdtions n n break end n n1 end irint Wewtons Method converged in d iterdtions n n1 The while statement says to keep doing whatever is between while and end until the condition is not satis ed anymore So this will run until f g 1e 7 6 Next we have our Newton iteration Then we check to see if we have hit the maximum number of iterations If so we quit and tell the user that Newton s Method did not converge After this if statement we increase n by 1 so that it will be different the next time through the while loop You can see that with the if statement this has the same behavior as the previous program Without the if statement this would run until convergence and never stop if you hit some maximum number of iterations b Rerun your new program using the same values as the previous program You should get the same results ricks We discuss some other tips and tricks to programming in Matlab 64 other tip a functions within functions You can c ate a function le and have functions de ned in that le that ONLY that function can use In other words let say I have my ewtonquots Method code Instead of de ning f by an inline function I can de ne it as a separate function known only by my Newtonquots Method code This is useful when you need to create some subroutines that only your function needs to use For example we can have function a 7riyprogrdmarN All the ewton s Method code here with fr dnd fpx being used but not de ned as inline functions function y fa y a 22ar8 function y fpa y 2172 Now try running your code You should get the same answer Type f1 at the Command Windowi Type fp1 either of these work why not Because f and fp exist ONLY as part of myprogrdm not as external functions b loops within loops You can of course have loops within loops within loopsetc This is sometimes nice when you are using matrices but you should use them ONLY when necessz y For example if I have two matrices of size 3 X 3 given by A and B I can nd C AB by fori 1J for j 13 0 CW 0 for k 13 CM 01 k 3 M and and and I would AVOID MULTIPLE LOOPS as much as possible There is no need to program matrix multiplication since A 6 B works perfectly ne and is much faster in Matlab Use built in Matlab functions and component wise arithmetic when possible They are always going to be signi cantly faster than what you write on your own cell arrays Every now and then you ll want to create an 39arrayquot which has different data types this isn t really an array but more of a container In other words I d like to create some structure that has a matrix a number and a string in it How can I do this The answer is cell arrays They allow you to create whatever object you want in any location of the cell The objects of the array are indexed by braces instead of I like with regular arrays An example of a cell array is c 1 2 3 44 Hello World7 Type this in Matlab then look at c1 and d3

### 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 signed up to be an Elite Notetaker with 2 of my sorority sisters this semester. We just posted our notes weekly and were each making over $600 per month. I 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."

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