Math 98 - Introduction to MATLAB Programming. Spring Lecture 3

Similar documents
Lecture 4: Matrices. Math 98, Spring Math 98, Spring 2018 Lecture 4: Matrices 1 / 20

Lecture 10: Powers of Matrices, Difference Equations

MAT 1302B Mathematical Methods II

CSCE 155N Fall Homework Assignment 2: Stress-Strain Curve. Assigned: September 11, 2012 Due: October 02, 2012

MATLAB BASICS. Instructor: Prof. Shahrouk Ahmadi. TA: Kartik Bulusu

Matrix-Vector Operations

Matrix-Vector Operations

22A-2 SUMMER 2014 LECTURE Agenda

Example Example Example Example

1 Overview of Simulink. 2 State-space equations

Math Assignment 3 - Linear Algebra

COMS 6100 Class Notes

WILEY. Differential Equations with MATLAB (Third Edition) Brian R. Hunt Ronald L. Lipsman John E. Osborn Jonathan M. Rosenberg

CS Homework 3. October 15, 2009

A First Course on Kinetics and Reaction Engineering Example S3.1

Note: The command name is upper case in the description given by help, but must be lower case in actual use. And the backslash Anb is dierent when A i

Introduction to Matlab

Matlab Exercise 0 Due 1/25/06

Math Camp Notes: Linear Algebra II

Finite Math - J-term Section Systems of Linear Equations in Two Variables Example 1. Solve the system

Introduction to Computational Neuroscience

(t) ), ( ) where t is time, T is the reaction time, u n is the position of the nth car, and the "sensitivity coefficient" λ may depend on un 1(

This appendix provides a very basic introduction to linear algebra concepts.

MOL410/510 Problem Set 1 - Linear Algebra - Due Friday Sept. 30

Section 4.1 The Power Method

1 R.V k V k 1 / I.k/ here; we ll stimulate the action potential another way.) Note that this further simplifies to. m 3 k h k.

Lab 2 Worksheet. Problems. Problem 1: Geometry and Linear Equations

Math/Phys/Engr 428, Math 529/Phys 528 Numerical Methods - Summer Homework 3 Due: Tuesday, July 3, 2018

PageRank: The Math-y Version (Or, What To Do When You Can t Tear Up Little Pieces of Paper)

Lab 2: Static Response, Cantilevered Beam

Properties of Linear Transformations from R n to R m

22A-2 SUMMER 2014 LECTURE 5

Optimization and Calculus

AMSC/CMSC 466 Problem set 3

Math 515 Fall, 2008 Homework 2, due Friday, September 26.

Designing Information Devices and Systems I Fall 2018 Homework 3

Numerical Linear Algebra

4. Linear transformations as a vector space 17

MATH 341 MIDTERM 2. (a) [5 pts] Demonstrate that A and B are row equivalent by providing a sequence of row operations leading from A to B.

Numerical Linear Algebra

Eigenvalues and Eigenvectors

MATH3200, Lecture 31: Applications of Eigenvectors. Markov Chains and Chemical Reaction Systems

= main diagonal, in the order in which their corresponding eigenvectors appear as columns of E.

Homework 6: Image Completion using Mixture of Bernoullis

Eigenvalue and Eigenvector Homework

Lecture 3: Special Matrices

CSCI 2033 Spring 2016 ELEMENTARY COMPUTATIONAL LINEAR ALGEBRA

Image Registration Lecture 2: Vectors and Matrices

COLUMN VECTORS a=[1;2;3] b. a(1) = first.entry of a

Exercise 1.3 Work out the probabilities that it will be cloudy/rainy the day after tomorrow.

Eigenvalues and eigenvectors

Matlab Instruction Primer; Chem 691, Spring 2016

Lecture 5b: Starting Matlab

3.3 Real Zeros of Polynomial Functions

[ Here 21 is the dot product of (3, 1, 2, 5) with (2, 3, 1, 2), and 31 is the dot product of

Homework Assignment 4 Root Finding Algorithms The Maximum Velocity of a Car Due: Friday, February 19, 2010 at 12noon

Designing Information Devices and Systems I Spring 2018 Homework 5

MATLAB and Mathematical Introduction Will be discussed in class on 1/24/11

Convex Optimization / Homework 1, due September 19

Designing Information Devices and Systems I Fall 2017 Homework 3

Math 552 Scientific Computing II Spring SOLUTIONS: Homework Set 1

Homework 1 Solutions

2. The Power Method for Eigenvectors

Model-building and parameter estimation

Designing Information Devices and Systems I Fall 2018 Homework 5

Econ Slides from Lecture 8

Using Microsoft Excel

New Mexico Tech Hyd 510

PowerPoints organized by Dr. Michael R. Gustafson II, Duke University

TOPIC 2 Computer application for manipulating matrix using MATLAB

Notes on singular value decomposition for Math 54. Recall that if A is a symmetric n n matrix, then A has real eigenvalues A = P DP 1 A = P DP T.

Math 304 Handout: Linear algebra, graphs, and networks.

Lab 1: Dynamic Simulation Using Simulink and Matlab

Math 504 (Fall 2011) 1. (*) Consider the matrices

1 Linearity and Linear Systems

chapter 5 INTRODUCTION TO MATRIX ALGEBRA GOALS 5.1 Basic Definitions

14. Properties of the Determinant

MATH 315 Linear Algebra Homework #1 Assigned: August 20, 2018

CSC 1700 Analysis of Algorithms: Warshall s and Floyd s algorithms

LAB 1: MATLAB - Introduction to Programming. Objective:

Image Compression Using Singular Value Decomposition

Section 29: What s an Inverse?

Gaussian Elimination and Back Substitution

Announcements. Problem Set 6 due next Monday, February 25, at 12:50PM. Midterm graded, will be returned at end of lecture.

Solution Set 7, Fall '12

VECTORS AND MATRICES

Laboratory 11 Control Systems Laboratory ECE3557. State Feedback Controller for Position Control of a Flexible Joint

Programming Assignment 4: Image Completion using Mixture of Bernoullis

The Principal Component Analysis

MATRICES. a m,1 a m,n A =

Multivariable Control Laboratory experiment 2 The Quadruple Tank 1

Class President: A Network Approach to Popularity. Due July 18, 2014

Introduction to Hartree-Fock calculations in Spartan

Math 103, Summer 2006 Determinants July 25, 2006 DETERMINANTS. 1. Some Motivation

Chapter 1 Linear Equations. 1.1 Systems of Linear Equations

Review of Basic Concepts in Linear Algebra

Designing Information Devices and Systems I Fall 2018 Lecture Notes Note Introduction to Linear Algebra the EECS Way

Problem set 1. (c) Is the Ford-Fulkerson algorithm guaranteed to produce an acyclic maximum flow?

Homework and Computer Problems for Math*2130 (W17).

Eigenvalues, Eigenvectors, and Diagonalization

Transcription:

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.

Exercise Remember the formula for the sum of n consecutive numbers 1 + 2 +... + n = We want to compute this number four ways n(n + 1) 2 1 Use the MATLAB function sum. Recall that we studied sum in lecture 2. 2 Set S=0. Use a for loop to redene S at each iteration. Compare to problem about tiling a disk in lecture 2. 3 Set S=0. Use a while loop to redene S at each step. Remember to update the number counting iterations. 4 Write a function called ConSum such that ConSum(n) equals 1 n(n + 1). 2.

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 Concepts functions, local variables matrices, matrix operations

(problem_3_1) Approximating square root Let A be a positive number. Think of A as the area of a square with side length A. We can construct a rectangle with side lengths L and W that has area A. This means 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 through averaging.

(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/ 1 2 (L + W ) 5 Repeat until L W is less than a tolerance Tol 6 Output L Here Tol is a small number reecting the accuracy of the approximation. Small tolerance implies good accuracy. We do not know how many times we must repeat the steps. Therefore we should use a while loop. While L-W >= Tol, we can repeat the steps.

Functions Remember the following terms 1 code: a statement to be executed by the computer. For example, a conditional 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 dierent from a script. function: a le containing a program. We call a function. For example, CalcCents(100). Note the le name is CalcCents.m.

Functions We have functions in addition to scripts because functions are 1 reusable A function replaces a repeated block of code in a program 2 simplifying A function organizes groups of code within a program. A function can be written in a separate le with its own variables. 3 changeable If procedures are packaged as a function, then they are easily accessed. Helpful for code that must be modied by user or programmer.

Functions The format for functions is 1 %%%Name.m%%% 2 f u n c t i o n [ o utput ] = Name( i n p u t ) 3 4 Code 5 6 end The name of the function should match the name of the M-le. Use a capital letter in le name to avoid conict with built-in MATLAB functions

Functions Remember that MATLAB has a built-in function for computing square root. It is sqrt. 1 %%% S q r t.m %%% 2 % Computes s q u a r e r o o t o f a number u s i n g MATLAB f u n c t i o n s q r t 3 % I n p u t : a p o s i t i v e number 4 % Output : t h e s q u a r e r o o t 5 % Example : S q r t ( 4 ) w i l l y i e l d 2 6 7 f u n c t i o n [ outputnumber ] = S q r t ( inputnumber ) 8 9 outputnumber=s q r t ( inputnumber ) ; 10 11 end

nargin The command nargin appears within the code for a function. It is the number of inputs specied by the user. 1 %%% S q r t.m %%% 2 % Computes s q u a r e r o o t o f a number u s i n g MATLAB f u n c t i o n s q r t 3 % I n p u t : a p o s i t i v e number 4 % Output : t h e s q u a r e r o o t 5 % Example : S q r t ( 4 ) w i l l y i e l d 2 6 7 f u n c t i o n [ outputnumber, x ] = S q r t ( inputnumber ) 8 x=n a r g i n ; 9 outputnumber=s q r t ( inputnumber ) ; 10 end

Testing Inputs We cannot assume that the user has correctly entered input. If the user enters incorrect input, then the function cannot be called. This makes it seem that there 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 to display comments in command window. Compare to help for built in MATLAB function. Checking that the input has the proper format can avoid an error caused by the user.

return The command return halts execution of a program. The user returns to the command window. 1 %%% S q r t.m %%% 2 % Computes s q u a r e r o o t o f a number u s i n g MATLAB f u n c t i o n s q r t 3 % I n p u t : a p o s i t i v e number 4 % Output : t h e s q u a r e r o o t 5 % Example : S q r t ( 4 ) w i l l y i e l d 2 6 7 f u n c t i o n [ outputnumber ] = S q r 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 n 11 e l s e 12 outputnumber=s q r t ( inputnumber ) ; 13 end 14 end

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 V a 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 end 8 9 V a r i a b l e s =[ V a r i a b l e s, e x i s t ( ' r ' ) ] ; 10 V a r i a b l e s =[ V a r i a b l e s, e x i s t ( ' t ' ) ] ; 11 12 z =2 (Add ( x, y ) ) ; 13 14 V a r i a b l e s =[ V a r i a b l e s, e x i s t ( ' r ' ) ] ; 15 V a r i a b l e s =[ V a 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?

Variables in Functions Remember that the Workspace is a special le called a MAT-le which contains the variables we have dened during our MATLAB session. MATLAB must allocate memory to call a function. Think of a function as having 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 dened, the variable 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 species x=7. Suppose we have x=-0.789 in the Workspace. There will not be an error. 4 After going through the code, MATLAB has the numbers generated by the program.matlab saves the numbers to the output variables specied by the user. These appear in the Workspace. 5 The MAT-le is deleted.

Variables in Functions This means that 1 Variables in functions are not global Variables in a function cannot be accessed or modied by other functions. Therefore variables within a function cannot conict with variables of the same name outside the function. 2 Variables in functions do not persist When the code in a function nishes execution, the values assigned to variables are not stored in the Workspace. See lecture 4 for more information on the scope of variables in functions.

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 to the line. It is called a break point Calling problem_3_1 will prompt the debugger.

Review of problem_3_1 We want to see how variables are stored during the execution of the program in problem_3_1. Try x = problem_3_1(8,1e-4). Remember that this is scientic notation for 10 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 the function being called. 3 Exit using dbquit. 4 Click on the red dot to make it disappear.

(exercise_3_1) Consider the following version of IsMagic.m the program from homework assignment 1. 1 i n p u t M a t r i x=i n p u t ( ' E n t e r a m a t r i x : ' ) ; 2 3 % sum o f t h e columns, rows, and d i a g o n a l s o f t h e i n p u t m a t r i x 4 sumcol = sum ( i n p u t M a t r i x ) ; 5 sumrow = sum ( t r a n s ( i n p u t M a t r i x ) ) ; 6 sumdiag1 = t r a c e ( i n p u t M a t r i x ) 7 sumdiag2 = t r a c e ( f l i p u d ( i n p u t M a t r i x ) ) ; 8 9 % Set r e s u l t = 1 i f a l l t h e sums a r e e q u a 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

(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 input Use [m,n] = size(inputmatrix) to calculate the number of rows (m) and number of columns. Check m == n Check m >= 3 Use 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 be magic(4).

(problem_3_2) Transition matrices Let Let x be a 4 1 column vec 0.32 0.17 0.11 0.46 P = 0.18 0.43 0.32 0.33 0.27 0.22 0.39 0.14 0.23 0.18 0.18 0.07 x 1 x = x 2 x 3 x 4

(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. x i is the probability of the system being in the ith state. For example x 1 = 0.4 means there is a 40% chance of the system being in state 1 Think of the (i, j)th entry of P as being the probability of transitioning from state 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.

(problem_3_2) Transition matrices We want to write a function called problem_3_2 such that 1 the function has two inputs P an n n matrix x an n 1 vector 2 the function outputs y = P x

Review of problem_3_2 The function problem_3_2 helps us study the likelihood of states of the system. In particular, we would like to study the probabilities as the process goes on for a long time. This means that we want to calculate P N x for N a large number. This kind of process is called a Markov process. See Chapter 7.1 of van Loan for more information on matrices and matrix operations.

(exercise_3_2) Take P to be 0.32 0.17 0.11 0.46 P = 0.18 0.43 0.32 0.33 0.27 0.22 0.39 0.14 0.23 0.18 0.18 0.07 We want to nd x such that x = P x. The probabilities of the system being in states 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 columns of Vect are eigenvectors of P. Note Val is a diagonal matrix consisting of eigenvalues. More precisely is approximately zero. What eigenvector are we looking for? P Vect - Vect Val