math 98 - introduction to matlab programmingcpoli/math98/lecture4.pdf · math 98 - introduction to...

27

Upload: dangquynh

Post on 25-Jul-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

Math 98 - Introduction to MATLAB Programming

Spring 2016 - Lecture 4

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Reminders

Instructor: Chris Policastro

Class Website:https://math.berkeley.edu/~cpoli/math98/spring2016.html

Assignment Submission:https://bcourses.berkeley.edu

Homework 3

1 Due February 11th by 11:59pm on bCourses.

2 See assignment description for hints. See section 9.2 of van Loan forinformation about Roman numerals.

3 You are encouraged to collaborate. Use the discussion page on bCourses.

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Lecture 4: Using functions to package code

1 Problems(problem_4_1) Approximating root of polynomial using bisecton (Chapter9.3 van Loan)(problem_4_2) Approximating root of polynomial using Newton's method(Chapter 14 Dorfman)

2 Conceptsrecursive function, function handleglobal variable, persistent variablesymbols

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Review of problem_2_2

The Fibonacci numbers are de�ned recursively by the rule

fn+2 = fn+1 + fn

where f0 = 0 and f1 = 1.

There exists a formula for computing the nth Fibonacci number

1√5

(ϕn − ϕn)

where

ϕ =1 +√5

2, ϕ =

1−√5

2

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Review of problem_2_2

Why would we want to use a recursive formula to compute fn instead of anexact formula?

We can try using the formula

1√5

(ϕn − ϕn)

where

ϕ =1 +√5

2, ϕ =

1−√5

2

However this will give us an inaccurate value. Remember that numericalarithmetic involves approximations that cause errors. We want to use simpleoperations like addition. This means that a recursive formula is better.

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

(exercise_4_1) Recursive functions

We want to write a function Fibonacci.m that computes the nth Fibonaccinumber.

Write three versions of the function

1 Fibonaccifor.m using a for loop

2 Fibonacciwhile.m while loop

3 Fibonaccirec.m using recursion

In the third approach, you need to call Fibonaccirec.m withinFibonaccirec.m

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

(exercise_4_1) Recursive functions

1 %%% F i b o n a c c i r e c .m %%%2 f u n c t i o n [ Number ] = F i b o n a c c i r e c (N)3

4 i f (N==0)5 Number = 0 ;6 e l s e i f (N==1)7 Number = 1 ;8 e l s e9 Number = F i b o n a c c i r e c (N−1) + F i b o n a c c i r e c (N−2) ;10 end11

12 end

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

(problem_4_1) Approximating root of polynomial using bisecton

Remember that if a continuous function f changes sign on the interval [L,R],that is,

f(L) · f(R) < 0

then f(x) = 0 for some x ∈ [L,R]. Take

sign(y) =

1 for y > 0

−1 for y < 0

0 for y = 0

Note that f(L) · f(R) < 0 is equivalent to

sign(f(L)) · sign(f(R)) < 0

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

(problem_4_1) Approximating root of polynomial using bisecton

How can we determine the value of x?

Take f to be a polynomial. For example, we can take f to be the cubicpolynomial

x3 + 2x2 + x− 1

Note that f(−3) < 0 and f(3) > 0. Take

L = −3 and R = 3.

We learned in problem_3_1 to approximate a square root through averages.See SquaringPlot.m

We can try to approximate the value of x in [L,R] by taking the average

L+R

2

See BisectionAnimation.m

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

(problem_4_1) Approximating root of polynomial using bisecton

We want to write a function called problem_4_1 to approximate the root of apolynomial f on an interval [L,R].Remember that an approximation means repeatedly updating a guess.Remember a repeated procedure is implemented with a loop. We need acondition for terminating the loop.

The loop should terminate if it has been running for too long or theapproximation is accurate.

This suggests that the function problem_4_1 have �ve inputs

1 polynomial f

2 points L and R with L < R

3 maximum number of iterationsRemember iteration means repetition

4 toleranceRemember tolerance is a small number re�ecting the accuracy of theapproximation

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Function handles

How can we input a function into another function?

Make sure that Fibonaccirec.m is saved in your current directory.

Type hFibonaccirec=@Fibonaccirec into the command line.

Make sure your Workspace is open. Otherwise type workspace.

What is hFibonaccirec? Is it a variable? Is it a function?

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Function handles

A variable for a function is called a function handle.

1 %%% Rat io .m %%%2 % Inpu t : f u n c t i o n hand l e hF f o r f u n c t i o n F . p o s i t i v e

number N.3 % Output : r a t i o F(N+1)/F(N)4

5 f u n c t i o n [ Number]=Rat i o (hF ,N)6

7 Number=hF(N+1)/hF (N) ;8

9 end

The function Ratio.m does not call the function Fibonaccirec.m. InsteadFibonaccirec.m is passed to Ratio.m as an input using the function handlehFibonaccirec.

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Anonymous Functions

If your funtion can be coded in one line, then you do not need to make an m-�lefor it.

Type hAddTwo=@(x)x+2 in the command line.

Note that hAddTwo is a function handle. It is the function handle for thefunction x+ 2.

Type hAddTwo(2) in the command line.

hAddTwo is an example of an anonymous function.

Anonymous functions are useful for short functions that do not require separatem-�les.

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Inline Functions

MATLAB has a data type called an inline function.

Type hAddTwoInline=inline(`x+2').

hAddTwoInline is an inline function created from the string `x+2'.

While hAddTwoInline behaves like hAddTwo, we have not speci�ed 'x' as avariable. It was treated by MATLAB as a variable because it is not a numberlike 2 or a symbol like +. This limitation makes hFuncAnon more useful.

Inline functions will be discontinued in a future release of MATLAB!

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Review of problem_4_1

We see that the �ve inputs for problem_4_1.m

1 polynomial f

2 points L and R with L < R

3 maximum number of iterations

4 tolerance

take the form

1 function handle df

2 numbers L and R

3 integer MaxIteration

4 small number Tolerance

The output is a number X where the polynomial f is small.

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

exercise_4_2

Modify problem_4_1.m to have two outputs

1 X the value where the polynomial is small

2 Flag

Take Flag equal to 1 if abs(df(X))<ToleranceTake Flag equal to 0 if abs(df(X))>=Tolerance

Remember that the loop in problem_4_1.m terminates after MaxIteration orif abs(df(X))<Tolerance. The number Flag tells how the loop terminated.

Can you add a print statement to provide more information?

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Review of problem_4_1: MAT-�le

Enter whos into the command line.

The workspace keeps track of variables. It records names, size, and data type.We want to keep track of variables by saving to a �le. While this �le will actlike the workspace, it can be stored, shared or loaded.

A MAT-�le is a �le formated as �lename.mat. Use this format to save variables.

Type clear all. Set x=10. Type save(`test.mat','x').

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Review of problem_4_1: Variables in Functions

1 %%%DoubleSum .m%%%2 f u n c t i o n [ z , V a r i a b l e s ]=DoubleSum ( x , y )3 Va r i a b l e s =[ e x i s t ( ' x ' ) ] ;4

5 f u n c t i o n t=Add( r , s )6 t=r+s ;7 end8

9 Va r i a b l e s =[ Va r i a b l e s , e x i s t ( ' r ' ) ] ;10 Va r i a b l e s =[ Va r i a b l e s , e x i s t ( ' t ' ) ] ;11

12 z=2∗(Add( x , y ) ) ;13

14 Va r i a b l e s =[ Va r i a b l e s , e x i s t ( ' r ' ) ] ;15 Va r i a b l e s =[ Va r i a b l e s , e x i s t ( ' t ' ) ] ;16 end

Can you call the subfunction in lines 5-7 called Add?

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Review of problem_4_1: Variables in Functions

This means that

1 Variables in functions are not global

Variables in a function cannot be accessed or modi�ed by other functions.Therefore variables within a function cannot con�ict with variables of thesame name outside the function.

2 Variables in functions do not persist

When the code in a function �nishes execution, the values assigned tovariables are not stored in the Workspace.

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Review of problem_4_1: Variables in Functions

We can change the local scope of variables by specifying persistent orglobal

1 persistent

If a variable is speci�ed as peristent, then it cannot be modi�ed from thecommand line or by other functions. However, its value will be saved in theWorkspace following its initialization.

2 global

If a variable is speci�ed as global, then can be accessed or modi�ed in thecommand line or by other functions.

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

(problem_4_2) Approximating roots of polynomial using Newton's method

Newton's method is an algorithm for approximating the value of a root usingthe function and its derivative. Suppose f and its derivative f ′ are de�ned atyold. We set

ynew = yold −f(yold)

f ′(yold)

Repeatedly updating the value of ynew results in better approximations. Herewe require that f ′(yold) 6= 0.

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

(problem_4_2) Approximating roots of polynomial using Newton's method

We want to write a function that approximates a root using Newton's method.We want the inputs to be

1 function

2 initial guess

3 maximum number of iterations

4 tolerance

We do not input the derivative of the function.

How can we di�erentiate a function?

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Symbolic Variables

Just like we can declare variables to be persistent or global, we can declarevariables to be symbols.

While MATLAB manipulates them like numbers, MATLAB never assigns thema value. Use

syms x y z

to declare symbols x, y, and z.

Type whos. What is the class of x,y,z?

We can do arithmetic with x,y,z. The expression are symbolic variables.

Type z=x+y. Set w=2*z. What is w?

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Symbolic Functions

We can de�ne symbolic functions using the format

f(x,y) = x+y

The input of a symbolic function is an expression involving symbolic variables.The output of a symbolic function is a symbolic variable.

What is f(x+2,y)? What is f(2,2)?

Note that expressions involving symbolic variables can contain numbers. Inparticular, we can evaluate a symbolic function at number.

Set valuesym=f(2,2) and valuedouble=double(f(2,2)). What is thedi�erence between valuesym and valuedouble?

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Symbolic functions

We can use a function handle to de�ne a symbolic function.

Set g= a©(x)x+2. De�ne symg(x)=g(x).

Note that g is a function handle. We evaluate g in the symbolic variable x toobtain an expression with symbolic variables. symg is a symbolic functionde�ned from the expression.

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Symbolic functions

We can di�erentiate symbolic functions using diff.

1 dersymg ( x )=d i f f ( g , x , 1 ) ;2

3 v a l u e=doub l e ( dersymg (2) ) ;

Here diff(g,x,1) means we di�erentiate the symbolic function g in thevariable x one time. Note that value is a number. It is the value of thederivative of g at 2.

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming

Review of problem_4_2

See lecture 5 for more information about the format of the inputs forproblem_4_2.m.

Spring 2016 - Lecture 4 Math 98 - Introduction to MATLAB Programming