math 98 - introduction to matlab programmingcpoli/math98/lecture3.pdf(problem_3_1) approximating...

25

Upload: others

Post on 26-Jan-2020

15 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Math 98 - Introduction to MATLAB Programming

Spring 2016 - Lecture 3

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

Page 2: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Reminders

Instructor: Chris Policastro

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

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

Homework 2

1 Due September 8th by 11:59pm on bCourses.

2 See assignment description for hints.

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

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

Page 3: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Exercise

Remember the formula for the sum of n consecutive numbers

1 + 2 + . . .+ n =n(n+ 1)

2.

We want to compute this number four ways

1 Use the MATLAB function sum. Recall that we studied sum in lecture 2.

2 Set S=0. Use a for loop to rede�ne S at each iteration. Compare toproblem about tiling a disk in lecture 2.

3 Set S=0. Use a while loop to rede�ne S at each step. Remember toupdate the number counting iterations.

4 Write a function called ConSum such that ConSum(n) equals 12n(n+ 1).

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

Page 4: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Lecture 3: Using functions to package code

1 Problems(problem_3_1) Approximating square root (Chapter 5.1 van Loan)(problem_3_2) Transition matrices (Chapter 7.1 van Loan)

2 Conceptsfunctions, local variablesmatrices, matrix operations

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

Page 5: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

(problem_3_1) Approximating square root

Let A be a positive number. Think of A as the area of a square with sidelength

√A.

We can construct a rectangle with side lengths L and W that has area A. Thismeans

A = L ·W

If L ≈W , then √A ≈ L ≈W

This gives an approximation to the number√A.

Let us start with some L and W . Let us bring them nearer in value throughaveraging.

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

Page 6: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

(problem_3_1) Approximating square root

We want to write a program to implement the following steps

1 If A = 0, then output 0.

2 Otherwise, start with L = A and W = 1.

3 Replace L by the average (L+W )/2

4 Replace W by W/ 12(L+W )

5 Repeat until |L−W | is less than a tolerance Tol

6 Output L

Here Tol is a small number re�ecting the accuracy of the approximation. Smalltolerance implies good accuracy.

We do not know how many times we must repeat the steps. Therefore weshould use a while loop. While |L-W| >= Tol, we can repeat the steps.

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

Page 7: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Functions

Remember the following terms

1 code: a statement to be executed by the computer. For example, aconditional statement. The code implements a procedure.

2 program: a collection of codes

3 debug: to remove errors from a program

4 script: a �le containing a program. We run a script. For example,run problem_1_1.m.

A function packages code. However, it is di�erent from a script.

function: a �le containing a program. We call a function. For example,CalcCents(100). Note the �le name is CalcCents.m.

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

Page 8: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Functions

We have functions in addition to scripts because functions are

1 reusableA function replaces a repeated block of code in a program

2 simplifyingA function organizes groups of code within a program. A function can bewritten in a separate �le with its own variables.

3 changeableIf procedures are packaged as a function, then they are easily accessed.Helpful for code that must be modi�ed by user or programmer.

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

Page 9: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Functions

The format for functions is

1 %%%Name .m%%%2 f u n c t i o n [ output ] = Name( i npu t )3

4 Code5

6 end

The name of the function should match the name of the M-�le. Use a capitalletter in �le name to avoid con�ict with built-in MATLAB functions

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

Page 10: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Functions

Remember that MATLAB has a built-in function for computing square root. Itis sqrt.

1 %%% Sqr t .m %%%2 % Computes squa r e r oo t o f a number u s i n g MATLAB

f u n c t i o n s q r t3 % Inpu t : a p o s i t i v e number4 % Output : the squa r e r oo t5 % Example : Sq r t (4 ) w i l l y i e l d 26

7 f u n c t i o n [ outputnumber ] = Sqr t ( inputnumber )8

9 outputnumber=s q r t ( inputnumber ) ;10

11 end

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

Page 11: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

nargin

The command nargin appears within the code for a function. It is the numberof inputs speci�ed by the user.

1 %%% Sqr t .m %%%2 % Computes squa r e r oo t o f a number u s i n g MATLAB

f u n c t i o n s q r t3 % Inpu t : a p o s i t i v e number4 % Output : the squa r e r oo t5 % Example : Sq r t (4 ) w i l l y i e l d 26

7 f u n c t i o n [ outputnumber , x ] = Sqr t ( inputnumber )8 x=na r g i n ;9 outputnumber=s q r t ( inputnumber ) ;10 end

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

Page 12: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Testing Inputs

We cannot assume that the user has correctly entered input. If the user entersincorrect input, then the function cannot be called. This makes it seem thatthere is an error in the function.

You must add comments in the �le that explain the proper format for inputs.You should include an example in the comments. Type help filename.m todisplay comments in command window. Compare to help for built in MATLABfunction.

Checking that the input has the proper format can avoid an error caused by theuser.

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

Page 13: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

return

The command return halts execution of a program. The user returns to thecommand window.

1 %%% Sqr t .m %%%2 % Computes squa r e r oo t o f a number u s i n g MATLAB

f u n c t i o n s q r t3 % Inpu t : a p o s i t i v e number4 % Output : the squa r e r oo t5 % Example : Sq r t (4 ) w i l l y i e l d 26

7 f u n c t i o n [ outputnumber ] = Sqr t ( inputnumber )8 i f ( n a r g i n ~= 1)9 f p r i n t f ( ' Read comments ! ' ) ;10 r e t u r n11 e l s e12 outputnumber=s q r t ( inputnumber ) ;13 end14 end

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

Page 14: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

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 3 Math 98 - Introduction to MATLAB Programming

Page 15: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Variables in Functions

Remember that the Workspace is a special �le called a MAT-�le whichcontains the variables we have de�ned during our MATLAB session.

MATLAB must allocate memory to call a function. Think of a function ashaving its own Workspace. MATLAB takes the following steps

1 We enter input to execute the function. MATLAB creates a MAT-�le.

2 MATLAB goes through the code. Each time a variable is de�ned, thevariable is saved in the MAT-�le.

3 MATLAB will not look other places for variable.It will not look in the WorkSpace.Suppose the code speci�es x=7. Suppose we have x=-0.789 in theWorkspace. There will not be an error.

4 After going through the code, MATLAB has the numbers generated by theprogram.MATLAB saves the numbers to the output variables speci�ed

by the user. These appear in the Workspace.

5 The MAT-�le is deleted.

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

Page 16: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Variables in Functions

This means that

1 Variables in functions are not globalVariables 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 persistWhen the code in a function �nishes execution, the values assigned tovariables are not stored in the Workspace.

See lecture 4 for more information on the scope of variables in functions.

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

Page 17: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Review of problem_3_1

The debugger is a tool to help locate errors in a code.

Click the dash next to lines 9 of problem_3_1.m. A red dot will appear next tothe line. It is called a break point

Calling problem_3_1 will prompt the debugger.

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

Page 18: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Review of problem_3_1

We want to see how variables are stored during the execution of the program inproblem_3_1.

Try x = problem_3_1(8,1e-4). Remember that this is scienti�c notation for10−4.

1 Use the command dbstep to go line by line through the code.

2 Use dbstack to check your spot in the code. This will tell you thefunction being called.

3 Exit using dbquit.

4 Click on the red dot to make it disappear.

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

Page 19: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

(exercise_3_1)

Consider the following version of IsMagic.m the program from homeworkassignment 1.

1 i n pu tMa t r i x=i npu t ( ' Ente r a mat r i x : ' ) ;2

3 % sum of the columns , rows , and d i a g o n a l s o f the i npu tmat r i x

4 sumCol = sum( i npu tMa t r i x ) ;5 sumRow = sum( t r a n s ( i n pu tMa t r i x ) ) ;6 sumDiag1 = t r a c e ( i n pu tMa t r i x )7 sumDiag2 = t r a c e ( f l i p u d ( i npu tMa t r i x ) ) ;8

9 % Set r e s u l t = 1 i f a l l the sums a r e equa l . Otherwise ,s e t r e s u l t = 0 .

10 r e s u l t = i s e q u a l ( sumCol , sumRow ' , sumDiag1∗ ones (1 , n ) ,sumDiag2∗ ones (1 , n ) ) ;

11

12 r e t u r n

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

Page 20: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

(exercise_3_1)

Try to make the following improvement.

1 Turn into a function

2 Use debugger to locate errors

3 Improve comments

4 Check user inputUse [m,n] = size(inputMatrix) to calculate the number of rows (m) andnumber of columns.Check m == nCheck m >= 3Use all to check that all entries are nonzero.Can you check that all entries are positive? Use Vector=inputMatrix(:)'to create a row vector. Consider the vector Vector01=(Vector > 0)If the user does not specify a matrix, then set the default input to bemagic(4).

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

Page 21: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

(problem_3_2) Transition matrices

Let

P =

0.32 0.17 0.11 0.460.18 0.43 0.32 0.330.27 0.22 0.39 0.140.23 0.18 0.18 0.07

Let x be a 4× 1 column vec

x =

x1

x2

x3

x4

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

Page 22: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

(problem_3_2) Transition matrices

Think of the entries of x as corresponding to four possible states of a system.Each state has a probability of occuring. xi is the probability of the systembeing in the ith state.

For example x1 = 0.4 means there is a 40% chance of the system being instate 1

Think of the (i, j)th entry of P as being the probability of transitioning fromstate j to state i during one step of a process.

We call P a transition matrix because

y = P · x

is the probability of the states after one step of the process.

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

Page 23: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

(problem_3_2) Transition matrices

We want to write a function called problem_3_2 such that

1 the function has two inputsP an n× n matrixx an n× 1 vector

2 the function outputs y = Px

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

Page 24: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

Review of problem_3_2

The function problem_3_2 helps us study the likelihood of states of thesystem. In particular, we would like to study the probabilities as the processgoes on for a long time.

This means that we want to calculate PNx for N a large number.

This kind of process is called a Markov process. See Chapter 7.1 of van Loanfor more information on matrices and matrix operations.

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

Page 25: Math 98 - Introduction to MATLAB Programmingcpoli/math98/lecture3.pdf(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side

(exercise_3_2)

Take P to be

P =

0.32 0.17 0.11 0.460.18 0.43 0.32 0.330.27 0.22 0.39 0.140.23 0.18 0.18 0.07

We want to �nd x such that x = Px. The probabilities of the system being instates 1,2,3,4 does not change during the process.

Use the command[Vect,Val]=eig(P)

to return a 4× 4 matrix Vect and a 4× 4 matrix Val. Note that the columnsof Vect are eigenvectors of P. Note Val is a diagonal matrix consisting ofeigenvalues. More precisely

P Vect - Vect Val

is approximately zero.

What eigenvector are we looking for?

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