lade matlab practicecastello/291/handouts/ladematlabpractice.pdflade matlab practice last update:...

27
LADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.) Lesson 2: Matrix Operations: Transposes and Inverses. Lesson 3: Matrix Operations: Gaussian Elimination. (Manipulation of matrix rows and columns.) Lesson 4: Creating M-Files: The Adjoint Formula for the Matrix Inverse. (Introduces common programming commands.) Lesson 5: Cramer’s Rule. (More practice with m-files and matrix manipulation.) Lesson 6: Symmetric, Skew-Symmetric, and Orthogonal Matrices. (More practice with m-files.) Lesson 7: Vector Spaces. (Creating augmented matrices, rand() function.) Lesson 8: Gram-Schmidt Orthogonalization. (More practice with m-files.) Lesson 9: Root Finding & Graphing. (Finding roots of polynomials, graphing functions.) Lesson 10: Eigenvalues and Eigenvectors. (Using the eig() function.) Lesson 11: Eigenvalues and Eigenvectors. (More practice with m-files, rand() function.) Lesson 12: Slope Fields and Solution Curves. Lesson 13: Plotting Second-Order Solution Families. (More practice with plotting.) Lesson 14: The Runge-Kutta Method. (Numerical solution of first-order ODEs; working with m-files.) Lesson 15: The Runge-Kutta Method for Systems. (Numerical solution of first-order sys- tems of ODEs; working with m-files.) Lesson 16: Stability and the Phase Plane 1

Upload: others

Post on 22-Jan-2020

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

LADE MATLAB Practice

LAST UPDATE: January 27, 2010

Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

Lesson 2: Matrix Operations: Transposes and Inverses.

Lesson 3: Matrix Operations: Gaussian Elimination. (Manipulation of matrix rows andcolumns.)

Lesson 4: Creating M-Files: The Adjoint Formula for the Matrix Inverse. (Introducescommon programming commands.)

Lesson 5: Cramer’s Rule. (More practice with m-files and matrix manipulation.)

Lesson 6: Symmetric, Skew-Symmetric, and Orthogonal Matrices. (More practice withm-files.)

Lesson 7: Vector Spaces. (Creating augmented matrices, rand() function.)

Lesson 8: Gram-Schmidt Orthogonalization. (More practice with m-files.)

Lesson 9: Root Finding & Graphing. (Finding roots of polynomials, graphing functions.)

Lesson 10: Eigenvalues and Eigenvectors. (Using the eig() function.)

Lesson 11: Eigenvalues and Eigenvectors. (More practice with m-files, rand() function.)

Lesson 12: Slope Fields and Solution Curves.

Lesson 13: Plotting Second-Order Solution Families. (More practice with plotting.)

Lesson 14: The Runge-Kutta Method. (Numerical solution of first-order ODEs; workingwith m-files.)

Lesson 15: The Runge-Kutta Method for Systems. (Numerical solution of first-order sys-tems of ODEs; working with m-files.)

Lesson 16: Stability and the Phase Plane

1

Page 2: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

1. Vector Operations.

(a) Enter the row vector v = [3 2 − 7] by typing v = [3,2,-7]

(b) Convert v to a column vector by typing v = v’ .

(c) Compute 2v by typing 2*v.

(d) Enter the column vector w =

−406

.

(e) Compute v + w by typing v + w .

(f) Compute the vector formed by cubing each element of w (type w.^3). The “.” beforethe operator causes each element of the vector to undergo the operation (see whathappens if you type w^2).

(g) Compute the vector formed by inverting each element of v (type 1./v).

(h) Compute the product vT w (type v’*w).

(i) Compute the vector u where [uj] = [vjwj] (type u = v.*w)

(j) Sum all the elements in v (type sum(v)).

(k) Create a zero column vector x ∈ R4 (type x = zeros(4,1)).

(l) Create a column vector x ∈ R4 of all ones (type x = ones(4,1)).

(m) Assign the values 0, 0.1, 0.2, . . . , 1 to the vector x (type x = 0:0.1:1).

(n) Make x a column vector.

2

Page 3: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

2. Matrix Operations: Transposes and Inverses.

(a) Enter the matrix A =

2 3 55 1 812 5 21

(type A=[2, 3, 5; 5, 1, 8; 12, 5, 21]).

(b) Show the first row of A by typing A(1,:) .

(c) Let’s find the transpose of A. Let B = AT (type B = A’).

(d) Show the second column of B by typing B(:,2) .

(e) Enter the matrix C =

2 5 13 1 55 8 5

(f) Find the solution y to the system Cy = v by typing y = C\v

(g) Compute the product AB (type A ∗B).

(h) Create a 3× 3 identity matrix by typing eye(3)

3

Page 4: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

3. Matrix Operations: Gaussian Elimination.

(a) Enter the matrix A =

2 3 55 1 812 5 21

(b) Let B = AT (type B = A’).

(c) Store a copy of B in the matrix H (type H = B).

(d) Reduce B to an echelon form by performing the following operations:

(1) R1 → R2 −R1 (type B(1,:) = B(2,:) - B(1,:) ).

(2) R2 → R2 − 3R1

(3) R3 → R3 − 5R1

(4) R2 → R2/13

(5) R3 → R3 − 28R2

(e) Transform the result of the above calculations to reduced row echelon form by performingthe following additional operation:

(6) R1 → R1 + 4R2

(f) Type help rref

(g) Use the command rref to find the reduced row echelon form for B (set B back to itsoriginal value by typing B = H before using the rref command).

(h) Enter the matrix C =

2 5 13 1 55 8 5

(i) Compute the inverse of C (type inv(C) ).

(j) Enter the row vector w = [3 2 − 7].

(k) Set v = wT .

(l) Find the solution y to the system Cy = v using the formula y = C−1v.

4

Page 5: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

4. Creating M-files: The Adjoint Formula for the Matrix Inverse.

(a) The first step in creating a program is to open an editing window. To create a newM-file, type the word edit at the MATLAB command prompt. The MATLAB editorwill open.

(b) On the first line of the file, type the following: function adjA = find adjoint(A).This tells MATLAB the name of your function (find adjoint), the input you will provide(the matrix A) and the output you desire (the adjoint matrix adjA).

(c) Hit the ENTER key once. Now we are going to write some comments. MATLABignores anything preceded by a percent-sign. Type% This function finds the adjoint of the nxn matrix A.

(d) From the File Menu select Save As. Switch to a directory that you’ll be able to findlater. Observe that in the File Name box, find adjoint.m has already been written.Click Save. The name (including the path) for your file now appears in the Title Barof the MATLAB editor.

(e) Hit the ENTER key twice and the TAB key once. Determine the number of rows inthe input matrix A by typing n = size(A,1). Hit the ENTER key once. Determinethe number of columns in the input matrix A by typing m = size(A,2).

(f) Since A is a square matrix the number of rows must equal the number of columns. So, ifn 6= m, we need to exit with an error message. Hit the ENTER key once. Type thefollowing:

if n ∼= m

fprintf(1,’\n The matrix is not square!\n’);adjA = [];

else

(g) Hit the ENTER key once. Type adjA = A. This assignment creates a matrix of thesame size as A.

(h) Hit the ENTER key once. Type for i = 1:n. Hit the ENTER key once and theTAB key once. Typefor j = 1:n.

These commands tell MATLAB that we are creating two loops. The outer loop is forthe rows (indexed by i) and the inner loop is for the columns (indexed by j).

(i) Hit the ENTER key once. We are going to create the submatrix of A obtained bydeleting its ith row. Type the following:

5

Page 6: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

% delete ith row

if i ∼= 1 & i ∼= n

M = [A(1:i-1,:); A(i+1:n,:)];

elseif i == 1

M = A(2:n,:);

elseif i == n

M = A(1:n-1,:);

end

Here is an explanation of the code listed above. The if – elseif – end command tellsMATLAB to compute M based upon the value of i. If i is not one (the first row) or n(the last row), use the expression M = [A(1:i-1,:); A(i+1,n)]. But if i is one, keeprows 2 through n. If i is n, keep rows 1 through n− 1.

In an if statement, we use the double equal sign “==” to mean identical to and weuse the tilde equal sign “∼=” to mean not identical to.

(j) Now we are going to delete the entries from the jth column of M using similar code. Hitthe ENTER key twice. Type the following:

% delete jth column

if j ∼= 1 & j ∼= n

M = [M(:,1:j-1) M(:,j+1:n)];

elseif j == 1

M = M(:,2:n);

elseif j == n

M = M(:,1:n-1);

end

(k) Save your work.

(l) Now we are going to replace the entries in adjA with the cofactors Aij. Hit the ENTERkey twice. Type the following:adjA(i,j) = (-1)^(i+j)*det(M);

(m) Hit the ENTER key twice. To end the two for loops, type the following:end % for j = 1:n

end % for i = 1:n

(n) Once the two loops have been completed, the matrix adjA is the cofactor matrix whichis the TRANSPOSE of the adjoint. Hit the ENTER key once. Type the following:adjA = adjA’

6

Page 7: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

(o) Hit the ENTER once and the BACKSPACE key 4 times. To close the very firstif-statement, type the following:end % if n∼= m

(p) Save your work. Go to the MATLAB command window. At the top of the window is abox displaying the name of the current directory. Click on the . . . button beside thebox to change to the directory where you saved the file find adjoint.m. To check thatyou have the correct directory, type pwd.

(q) Enter the matrix A =

2 3 55 1 812 5 −1

.

(r) Save the inverse of A in the matrix B.

(s) We are going to compute the adjoint of A using the M-file we have created. Type C =

find adjoint(A).

(t) Type D = C/det(A).

(u) Type D*A. Is the answer what you expected (within computer roundoff error)?

(v) Type D-B. Is the answer what you expected (within computer roundoff error)?

7

Page 8: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

5. Cramer’s Rule.

(a) We are going to create a new M-file. If the MATLAB editor is still open, select theNew command from the File menu; otherwise, in the MATLAB command window,type edit.

(b) Type the following commands into the MATLAB editor window:function x = cramers rule(A,b)

% this function solves the system Ax = b

% when A is an nxn matrix invertible matrix

n = size(A,1);

m = size(A,2);

if n ∼= m

fprintf(1,’\n The matrix is not square!\n’);x = [];

else

detA = det(A);

if det(A) ∼= 0

x = zeros(n,1);

for j = 1:n

if j∼= 1 & j∼= n

Ab = [A(:,1:j-1) b A(:,j+1:n)];

elseif j==1

Ab = [b A(:,2:n)];

elseif j==n

Ab = [A(:,1:n-1) b];

end

x(j) = det(Ab)/detA;

end % for j=1:n

else

fprintf(1, ’\n The matrix A has a zero determinant \n’);x = [ ];

end %if det(A) ∼= 0

end %if n∼=m

(c) Save your work.

(d) The command fprintf is used to write information to the screen (or to a file). Providea line-by-line interpretation of the code cramers rule.m.

(e) Return to the MATLAB command window. Enter the matrix A =

1 4 54 2 5−3 3 −1

(f) Enter the COLUMN vector b = (2, 3, 1).

8

Page 9: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

(g) Use cramers rule.m to solve the problem Ax = b by typing x = cramers rule(A,b).

9

Page 10: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

6. Symmetric, Skew-Symmetric, and Orthogonal Matrices.

If A = AT , we say that A is symmetric. If A = −AT , we say that A is skew-symmetric. IfA−1 = AT we say that A is orthogonal. For example, the matrices

R =

1 3 −23 0 5

−2 5 4

and S =

0 2 1−2 0 −4−1 4 0

T =

2/3 1/3 2/3−2/3 2/3 1/3

1/3 2/3 −2/3

are symmetric, skew-symmetric, and orthogonal respectively.

(a) Using MATLAB, show that R−RT = 0, S− (−ST ) = 0, and T−1 −TT = 0.

(b) The following code tests whether a given matrix is symmetric, skew-symmetric, and/ororthogonal.

function transfun(A)

m = size(A,1);

n = size(A,2);

if n∼=mfprintf(1,’\nError! The matrix is not square!\n’);

else

if A == A’

fprintf(1,’\nThe matrix is symmetric!\n’);else

fprintf(1,’\nThe matrix is not symmetric!\n’);end

if A == -A’

fprintf(1,’\nThe matrix is skew-symmetric!\n’);else

fprintf(1,’\nThe matrix is not skew-symmetric!\n’);end

if inv(A) == A’

fprintf(1,’\nThe matrix is orthogonal\n’);else

fprintf(1,’\nThe matrix is not orthogonal!\n’);end

end

Test the code on the following matrices:

A =

3 1 51 0 −75 −7 9

and B =

0 9 −12−9 0 2012 −20 0

C =

1 0 00 1 00 0 1

10

Page 11: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

Even if a square matrix is neither symmetric nor skew-symmetric, it can be decomposed asthe sum of a symmetric matrix and a skew-symmetric matrix. Specifically A = A1 + A2

where A1 = 0.5(A + AT ) and A2 = 0.5(A−AT ).

(c) Use the MATLAB program editor to create an m-file to decompose any square matrix asthe sum of a symmetric matrix and a skew-symmetric matrix. The code should printA1 and A2 or return an error message if A is not square. Include your code when youturn in the project.

(d) Test your code on the following matrices:

U =

3 12 01 −5 19 1 8

and V =

1 0 12 −1 04 0 6

11

Page 12: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

7. Vector Spaces.

(a) Enter the matrix A =

[−4 0 −4 3−4 1 −1 1

](b) Type help null

(c) Find all solutions to the linear system of equations Ax = 0 by typing null(A).

(d) Now type null(A, ’r’). What do you observe?

(e) Enter the vectors u = (2, 0,−1, 3, 4), v = (1, 0, 0,−1, 2), and w = (0, 1, 0, 0,−1).

(f) Let B be the matrix whose columns are u, v, and w. Type B = [u v w]

(g) Type help rref as a reminder of how to use the rref command.

(h) Use the rref command to determine if these three vectors are linearly independent.

(i) See if the vector x = (2, 1,−2, 9, 3) can be written as a linear combination of u, v, w. Todo this, we solve Bc = x so we need to row reduce the augmented matrix [B x]. Typeaug = [B x]. Then use the rref command. What do you observe?

(j) See if the vector z = (−1, 12, 3,−14,−14) can be written as a linear combination of u,v, w. What do you observe?

(k) Use MATLAB to randomly generate three vectors from R3. Type y1 = rand(3,1)

and hit ENTER. Then type y2 = rand(3,1) and hit ENTER. Finally, type y3 =

rand(3,1) and hit ENTER.

(l) Let C be the matrix whose columns are y1, y2, and y3. Find the determinant of C bytyping det(C).

(m) Find the inverse of C by typing inv(C).

(n) Type rref(C). How does this support the information you obtained in parts (l) and(m)?

12

Page 13: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

8. Gram-Schmidt Orthogonalization.

(a) We are going to create a new M-file. In the MATLAB command window, type edit.

(b) Type the following commands into the MATLAB editor window:

function [W, U] = gram schmidt(V)

% Input matrix V; Output matrices W and U

% The columns of matrix V form a basis for vector space V

% The columns of matrix W are an orthogonal basis for vector space V

% The columns of matrix U are an orthonormal basis for vector space V

% initialization of variables

m = size(V,1);

n = size(V,2);

W = zeros(m,n);

U = W;

for j = 1:n

W(:,j) = V(:,j);

if j > 1

for k = 1:j-1

pk = ((V(:,j)’*W(:,k))/norm(W(:,k))^2)*W(:,k);

W(:,j) = W(:,j) - pk;

end % for k = 1:j-1

end % if j > 1

U(:,j) = W(:,j)/norm(W(:,j),2);

end % for j = 1:n

% end function gram schmidt

(c) Save your work.

(d) Return to the MATLAB command window. We would like to test the code using thefollowing vectors: v1 = (1, 3,−1, 2), v2 = (0,−4, 5, 1), v3 = (−7, 2, 1, 0). Create thematrix V using these vectors.

(e) Use gram schmidt.m to find an orthonormal basis constructed from v1,v2,v3 by typing[W, U] = gram schmidt(V).

13

Page 14: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

9. Root Finding & Graphing.

We would like to determine the roots of

z(m) = m4 + m3 − 3m2 − 5m− 2 = 0

which is a 4th degree polynomial. There are two ways we can use MATLAB to help us findthe roots.

1. Type help plot to learn about the plot command.

2. To create a vector, m, of 1000 input points in the interval (-10, 10),type m = linspace(-10 10 1000);

3. To create a vector, z, of 1000 output points corresponding to m,type z = m.^4 + m.^3 -3*m.^2 - 5*m - 2;

4. To plot the equation, z(m), type plot(m,z)

5. To adjust the portion of the graphic displayed, type axis([-4 4 -10 10])

6. To turn on the grid, type grid on

7. To print your graph, select the Print command from the File menu.

8. Observe that the graph appears to cross the line z = 0 in two places: m = −1 andm = 2. This means that (m + 1) and (m − 2) are factors of the equation. Hence(m + 1)(m− 2) = m2 −m− 2 is also a factor of the equation. Show that

z(m) = (m2 −m− 2)(m2 + 2m + 1).

What are the other two roots of z(m)?

9. Type help roots to learn about the roots command.

10. Use the roots command to determine the roots of the polynomial.

14

Page 15: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

10. Eigenvalues and Eigenvectors

1. At the Matlab command prompt, type help eig to learn about the eig command.

2. Let A be the matrix shown below.

A =

2 3 55 1 812 5 21

Enter this matrix into MATLAB.

3. Type [S, D] = eig(A).

4. Show that A is diagonalizable by typing S*D*inv(S).

15

Page 16: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

11. Eigenvalues and Eigenvectors of Symmetric Matrices.When A is an n × n real symmetric matrix, all the eigenvalues of A are real. We may usethe expression

xT Ax

xT x,

which called the Rayleigh-Ritz ratio, to estimate the value of the smallest and largest eigen-values of A:

λmin = minx 6=0

xT Ax

xT x= min

xT x=1xT Ax (1)

λmax = maxx 6=0

xT Ax

xT x= max

xT x=1xT Ax (2)

(a) Use the MATLAB program editor to create the following m-file:function [S, D] = evalues(A,num iter)

% function [S, D] = evalues(A,num iter)

%

% This function prints an estimate of the maximum

% and minimum eigenvalues for the square matrix A

% provided that A is symmetric; it also prints the

% true eigenvalues in the diagonal matrix D

% and corresponding eigenvectors in the matrix S

%

% The two input parameters are the matrix A and

% the number of iterations, num iter, to run

Asize = size(A);

if Asize(1) ∼= Asize(2)

fprintf(1,’\nError! The matrix is not square!\n’);S = [ ];

D = [ ];

else

if ∼(isequal(A,A’))fprintf(1,’\nWarning! The matrix is not symmetric!\n’);

end

n = Asize(1);

x = zeros(n,num iter);

l = zeros(num iter,1);

min iter = 0;

max iter = 0;

lmin = inf;

lmax = -inf;

for i = 1:num iter

y = 2*rand(n,1)-1;

16

Page 17: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

if y’*y ∼= 0

x(:,i) = y /(y’*y)^0.5;

l(i) = x(:,i)’*A*x(:,i);

if l(i) < lmin

lmin = l(i);

min iter = i;

end

if l(i) > lmax

lmax = l(i);

max iter = i;

end

end

end

fprintf(1,’\n Smallest eigenvalue (estimated): %f\n’, lmin);

fprintf(1,’\n Largest eigenvalue (estimated): %f\n’, lmax);

fprintf(1,’\n The true eigenvalues and eigenvectors are\n’);[S, D] = eig(A);

end % Asize(1) ∼= Asize(2)

% end function

(b) Provide an explanation for the code. (If necessary, use the MATLAB help to lookupany functions with which you are not familiar.)

(c) Test the code on the following matrices

A =

8 1 11 8 11 1 8

B =

1 2 32 4 53 5 6

C =

3 0 0−4 6 216 −15 −5

(d) Explain what you observed in part (c).

17

Page 18: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

12. Slope Fields and Solution Curves(For more details, see Section 1.3 of Edwards & Penney, 3rd ed.)

Consider a differential equation of the form

dy

dx= f(x, y).

We are able to solve this DE in only a few specific cases (e.g., separable, linear, exact, etc.)For example, we none of the methods we will learn will allow us to solve the ODE

y′ = x2 + y2

in terms of ordinary functions. However, we can use a graphical method to construct ap-proximate solutions. The graph, called a slope field is discussed in detail in Section 1.3. Wewill use some prepared MATLAB code to create slope fields.

The following assumes you are using MATLAB 7

(a) Download the file dfield7.m from http://math.rice.edu/∼dfield/. Be sure store it in alocation where you’ll be able to find it.

If you are using some other version of MATLAB, you will need to download the ap-propriate dfield#.m file from http://math.rice.edu/∼dfield/.

(b) Change the current directory being used by MATLAB to the location where you’vestored the file. (The Current Directory drop-down list should appear at the top ofthe MATLAB window.)

(c) At the MATLAB command prompt, type dfield7 and hit ENTER. This action opensa dialog box similar to the one displayed on page 30 of the course text.

(d) Fill in the dialog box as shown in Figure 1.3.29 in the course text. When you are done,left-click the Proceed button.

(e) A display window will appear showing the slope field for the differential equation. Nowwe are going to add a few solution curves to the display. From the display window’sOptions menu, select Plot several solutions.

(f) Click on five different points in the slope field then hit ENTER. Your graph shouldnow look similar to that shown in Figure 1.3.28 in the text.

(g) Click the Print button on the display window to print your graph. Then Click theQuit button to close the display and setup windows.

(h) Use dfield7.m to plot the slope field and several solution curves for the differentialequation

y′ = x2 − y

for −3 ≤ x, y ≤ 3. Print out your graph when you are done.

18

Page 19: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

(i) Use dfield7.m to plot the slope field and several solution curves for the differential equa-tion

y′ = x2 + y2

for −3 ≤ x, y ≤ 3. Print out your graph when you are done.

19

Page 20: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

13. Plotting Second-Order Solution Families.See pages 300–301 of Edwards & Penney, 3rd ed. for additional details.

Please reproduce Figures 5.1.6 and 5.1.7 using the MATLAB commands on pages 300–301. Then modify your command-line code to construct a family of solution curves for thefollowing problems:

(a) y′′ − 5y′ + 6y = 0 y(0) = 1 y′(0) = b

(b) y′′ − 5y′ + 6y = 0 y(0) = a y′(0) = 1

(c) y′′ + 3y′ + 3y = 0 y(0) = 1 y′(0) = b

(d) y′′ + 3y′ + 3y = 0 y(0) = a y′(0) = 1

20

Page 21: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

14. The Runge Kutta Method(For more details, see Sections 2.3 and 2.6 of Edwards & Penney, 3rd ed.)

A crossbow bolt is shot straight up from the ground (y(0) = 0) with initial velocity v(0) =49 m/s. Assuming that air resistance is proportional to squared velocity, the velocity of thecrossbow bolt satisfies

dv

dt= −0.0011v|v| − 9.8, v(0) = 49.

We are going to use the Runge-Kutta method to analyze the motion of the bolt.

(a) Download the following file from the course website and be sure to store it in a locationwhere you’ll be able to find it

crossbow.m

(b) Change the current directory being used by MATLAB to the location where you’vestored the file. (The Current Directory drop-down list should appear at the top ofthe MATLAB window.)

(c) At the MATLAB command prompt, type crossbow and hit ENTER.

(d) First we are going to use the Runge-Kutta method to estimate v(t) for 0 ≤ t ≤ 10 using400 subintervals.

At the prompt, enter 0 for the initial position then hit ENTER. Enter 49 for theinitial position then hit ENTER. Enter 0 for the initial time then hit ENTER. Enter10 for the end time then hit ENTER. Enter 400 for the number of intervals then hitENTER.

(e) Print the graph of the skydiver’s velocity as a function of time. Close the graph window.

(f) We can estimate y(t), the position of the crossbow bolt, using the data we’ve alreadygenerated:

yn+1 = yn + vnh + 0.5anh2

(See discussion prior to problem 29 on p.140). Print the graph of the skydiver’s positionas a function of time. Close the graph window.

The bolt’s true position and velocity functions during ascent and descent are given bythe formulas:

Ascent:

v(t) = 94.388 tan (0.478837− 0.103827t),

y(t) = 108.465 + 909.091 ln (cos (0.478837− 0.103827t))

21

Page 22: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

Descent:

v(t) = −94.388 tanh (0.103827[t− 4.6119]),

y(t) = 108.465− 909.091 ln (cosh (0.103827[t− 4.6119]))

We are going to create graphs of the true velocity and position. The maximum heightis achieved around t = 4.6119s.

(g) First we need to provide the time values at which the velocity and position will be eval-uated. At the command prompt, type tup = linspace(0,4.6119,1000); and pressENTER. Now, type tdown = linspace(4.6119,10,1000); and press ENTER.

(h) Next, we need to evaluate v(t) for 0 ≤ t ≤ 10. At the command prompt, type vup =

94.388*tan(0.478837 - 0.103827*tup); and press ENTER. Now, type vdown =

-94.388*tanh(0.103827*(tdown - 4.6119)); and press ENTER.

(i) Next, we need to evaluate y(t) for 0 ≤ t ≤ 10. At the command prompt, type yup

= 108.465 + 909.091*log(cos(0.478837 - 0.103827*tup)); and press ENTER.Now, type ydown = 108.465 - 909.091*log(cosh(0.103827*(tdown - 4.6119)));

and press ENTER.

(j) Now we are going to create and print the velocity versus time graph. At the com-mand prompt, type plot(tup,vup,tdown,vdown) and press ENTER. Then typexlabel(’Time’) and press ENTER. Then type ylabel(’True Velocity’) and pressENTER. Then type title(’True Velocity Function’)and press ENTER. Printyour graph and close the graph window.

(k) Now we are going to create and print the position versus time graph. At the com-mand prompt, type plot(tup,yup,tdown,ydown) and press ENTER. Then typexlabel(’Time’) and press ENTER. Then type ylabel(’True Position’) and pressENTER. Then type title(’True Position Function’)and press ENTER. Printyour graph and close the graph window.

(l) Compare the true position and velocity graphs to the ones you created using the Runge-Kutta method.

22

Page 23: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

15. The Runge Kutta Method for Systems.(For more details, see Section 7.6 of Edwards & Penney, 3rd ed.)

Consider the following system of nonlinear first-order ODEs:

x′ = 0.2x− 0.005xy (3)

y′ = −0.5y + 0.01xy.

This system describes a predator-prey model where x(t) gives the number of prey and y(t)gives the number of predators at any time t. This model could be used to explain populationdynamics of foxes and rabbits in a closed environment. There are no known methods fordetermining an solution to this system in terms of elementary functions. Thus, we are forcedto use numerical methods.

(a) Download the following file from the course website and be sure to store it in a locationwhere you’ll be able to find it

predprey.m

(b) Change the current directory being used by MATLAB to the location where you’vestored the file. (The Current Directory drop-down list should appear at the top ofthe MATLAB window.)

(c) At the MATLAB command prompt, type predprey and hit ENTER.

(d) At the prompt, enter 10 for the initial x value then hit ENTER. Enter 10 for the initialy value then hit ENTER. Enter 0 for the initial time then hit ENTER. Enter 100for the end time then hit ENTER. Enter 1000 for the number of intervals then hitENTER.

(e) Print the graph of the population dynamics. Describe what you observe. (For example,what are the max/min population levels? What is the average cycle time? Can youexplain why the populations are “out of phase” with each other?)

(f) Close the graph window. Return to the MATLAB command window.

(g) Rerun the example (steps (c) through (f)) using the initial conditions x(0) = 70, y(0)= 40.

(h) Rerun the example (steps (c) through (f)) using the initial conditions x(0) = 40, y(0)= 70.

(i) Describe what you observe about the impact of initial conditions on the population level.

23

Page 24: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

(j) Now we are going to consider a population model given by the equations:

x′ = 14x− 0.5x2 − xy (4)

y′ = 16y − 0.5y2 − xy.

This model describes how species x and y compete against each other for the food avail-able in their common environment. At the MATLAB prompt, type edit predprey.m

then hit ENTER.

(k) When the editor window opens, select Save As from the File Menu and save the filewith the name predprey2.m in a location that you will remember.

(l) Scroll to the end of the file. We are going to change the labels on our graph. Changethe title (line 37) to Competition System by deleting what is there and typingtitle(’Competition System’). Next, change the legend (line 38) by deleting whatis there and typing legend(’x(t)’, ’y(t)’)

(m) Next, we are going to change line 42 (the definition of the function f) from what isgiven to f = 14x − 0.5x2 − xy as follows: delete what is listed and type in f = 14*x

- 0.5*x^2 - x*y

(n) Now we are going to change line 46 (the definition of the function g) from what is givento g = 16y − 0.5y2 − xy as follows: delete what is listed and type in g = 16*y -

0.5*y^2 - x*y

(o) Save the file and return to the command window. At the command prompt, typepredprey2 and hit ENTER.

(p) Run the model using the initial conditions x(0) = 100, y(0) = 60. Run the model untilt = 3 using 1000 intervals. Print the graph.

(q) Run the model using the initial conditions x(0) = 60, y(0) = 100. Run the model untilt = 3 using 1000 intervals.

(r) Explain what you observed in steps (p) and (q).

24

Page 25: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

16. Stability and the Phase Plane.(For more details, see Sections 9.1–9.3 of Edwards & Penney, 3rd ed.)

A wide variety of natural phenomena are modeled by two-dimensional first-order systems ofthe form

dx

dt= F (x, y) (5)

dy

dt= G(x, y)

in which the independent variable t does not appear. Such a system is said to be autonomous.We assume that F (x, y) and G(x, y) are continuously differentiable in some region R of thexy-plane. This region is called the phase plane.

Given any t0 and any point (x0, y0) there is a unique solution (x(t), y(t)) satisfying the initialconditions x(t0) = x0, y(t0) = y0. Such a solution is called a trajectory.

When F and G are nonlinear, it is almost impossible to determine x(t) and y(t). We arethen forced to analyze the behavior of the system qualitatively. One way to do this is to usea phase plane portrait.

Open a workspace in MATLAB by selecting the program from the Start Menu. When youare finished with this project, print the commands and results shown in the command win-dow by selecting File/print. Note: The output can be quite long if you have been workingin MATLAB for some time. You can save the command window display into a text file, editit, and print it later if you choose.

Part 1: Working with PPLANE.Helpful Reading: pp. 529–530 of Edwards & Penney, 3rd ed.

The following assumes you are using MATLAB 7

(a) Download the file pplane7.m from http://math.rice.edu/∼dfield/. Be sure store it in alocation where you’ll be able to find it.

If you are using some other version of MATLAB, you will need to download the ap-propriate pplane#.m file from http://math.rice.edu/∼dfield/.

(b) Change the current directory being used by MATLAB to the location where you’vestored the file. (The Current Directory drop-down list should appear at the top ofthe MATLAB window.)

(c) At the MATLAB command prompt, type pplane7 and hit ENTER. This action opensa dialog box similar to the one displayed on page 529 of the course text.

25

Page 26: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

(d) Fill in the dialog box as shown in Figure 9.1.20 in the course text. When you are done,left-click the Proceed button.

(e) A display window will appear showing the phase plane portrait for the system. Now weare going to add a few solution trajectories to the display. From the display window’sSolutions menu, select Plot several solutions.

(f) Click on five different points in the phase portrait then hit ENTER. What does thisgraphic tell you about typical solutions to this system of ODEs?

(g) Click the Print button on the display window to print your graph. Then Click theQuit button to close the display and setup windows.

(h) Solve (by hand) the system of equations

dx

dt= −x (6)

dy

dt= −2y

(Observe that this is the system for which you created the phase portrait.) Explainhow the analytical solution supports what you learned from the phase portrait.

Part 2: Ecological Systems.

Unlike the problem examined in Part 1, we are usually unable to solve (1) analytically. Acritical point of the system (1) is a point (x∗, y∗) where F (x∗, y∗) = G(x∗, y∗) = 0. Thebehavior of the trajectories near an isolated critical point of an autonomous system is ofparticular interest.

The Jacobian matrix for (1) is the following matrix of partial derivatives:

J =

∂F∂x

∂F∂y

∂G∂x

∂G∂y

To determine the behavior of the critical point (x∗, y∗) we look at the eigenvalues of J(x∗, y∗).If the eigenvalues are:

• Real, unequal, same sign. Then the critical point is either a source (both eigenval-ues positive; trajectories flow out) or sink (both eigenvalues negative; trajectories aresucked in)

• Real, unequal, opposite signs. Then the critical point is a saddle and the trajectorieslook like hyperbolas.

• Complex conjugates. Then the critical point is a spiral. The trajectories spiral awayfrom the critical point if the real part of the eigenvalues is positive; they spiral introthe critical point if the real part of the eigenvalues is negative.

26

Page 27: LADE MATLAB Practicecastello/291/Handouts/LADEMatlabPractice.pdfLADE MATLAB Practice LAST UPDATE: January 27, 2010 Lesson 1: Vector Operations. (Entering vectors, transposition, multiplication.)

• Pure imaginary. The then critical point is a center. The trajectories circle around thecritical point.

We will illustrate with an example.

Let x(t) and y(t) represent two different animal populations in some closed environment.Suppose the populations are governed by the following system of equations:

dx

dt= 14x− 2x2 − xy (7)

dy

dt= 16y − 2y2 − xy

(a) Find the four critical points (x∗, y∗) for the system.

(b) Next we need to find the eigenvalues for J(x∗, y∗) for each of the 4 critical points. Youcan do this by hand or use the MATLAB command [S, D] = eig(J).

(c) Determine the appropriate characterization for each of the critical points. (Of the fourcritical points there are 2 saddle points, one source node and one sink node.)

(d) Now use pplane7.m to draw the phase plane portrait for this system.

(e) We are going to add the critical points to the drawing. From the Solutions menu, selectFind an equilibrium point. Left-click near (0,0). (You can ignore the small dialogbox that appears.) Repeat this procedure for the three remaining critical points.

(f) Now we are going to add a few solution trajectories to the display. From the displaywindow’s Solutions menu, select Plot several solutions. Click on at least differentpoints in the phase portrait, close to but not on the critical points, then hit ENTER.The more trajectories you plot, the more your graphic will look like Figure 9.3.13.

(g) Click the Print button on the display window to print your graph. Then Click theQuit button to close the display and setup windows.

(h) Discuss what the phase plane portrait and your analysis of the critical points tells youabout the behavior of the two populations depending on the initial conditions.

27