mat lab practice

16
MATLAB Practice Lesson 1:  Vector Operations. (Entering vectors, transposition, multiplication.) Lesson 2:  Matrix Operations: Transposes and Inverses. Lesson 3:  Mat rix Operat ions: Gauss ian Elimina tion. (Man ipulat ion of matrix rows and columns.) Lesson 4:  Cre ati ng M-F ile s: The Adjoint Formula for the Mat rix Inv ers e. (Introd uce s common programming commands.) Lesson 5:  Cramer’s Rule. (More practice with m-les and matrix manipulation.) Lesson 6:  Symmetric, Skew-Sy mmetr ic, and Orthogonal Matric es. (Mor e practice with m-les.) Lesson 7:  Vector Spaces. (Creating augmented matrices,  rand()  function.) Lesson 8:  Gram-Schmidt Orthogonalization. (More practice with m-les.) 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-les,  rand()  function.) 1

Upload: leke-ogunranti

Post on 02-Jun-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 1/16

MATLAB Practice

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.)

1

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 2/16

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  =

−4

06

.

(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 [u j] = [v jw j] (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

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 3/16

Matrix Operations: Transposes and Inverses.

(a)   Enter the matrix  A  =

2 3 5

5 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 1

3 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

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 4/16

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 5/16

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, if n = m, we need to exit with an error message. Hit the ENTER key once. Type thefollowing:

if n   ∼= mfprintf(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

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 6/16

% 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 == nM = 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 we

use the tilde equal sign “∼=” to mean  not identical to.

(j)  Now we are going to delete the entries from the j th 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 == nM = 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:nend % 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

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 7/16

(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 a

box 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 5

5 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

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 8/16

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 = [];

elsedetA = 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 5

4 2 5−3 3   −1

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

8

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 9/16

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

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 . If A−1 = AT  we say that A is  orthogonal . For example, the matrices

R =

1 3   −2

3 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∼=m

fprintf(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

9

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 10/16

Test the code on the following matrices:

A =

3 1 5

1 0   −75   −7 9

  and   B =

0 9   −12−9 0 2012   −20 0

  C =

1 0 0

0 1 00 0 1

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 0

1   −5 19 1 8

  and   V   =

1 0 1

2   −1 04 0 6

10

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 11/16

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)?

11

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 12/16

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

e n d % i f 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).

12

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 13/16

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.

13

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 14/16

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 5

5 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).

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=0

xT Ax

xT x  = min

xT x=1xT Ax   (1)

λmax   = maxx=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’);

14

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 15/16

S = [ ];

D = [ ];

else

if   ∼(isequal(A,A’))

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

endn = 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 itery = 2*rand(n,1)-1;

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.)

15

8/10/2019 Mat Lab Practice

http://slidepdf.com/reader/full/mat-lab-practice 16/16

(c)  Test the code on the following matrices

A =

8 1 1

1 8 11 1 8

  B =

1 2 3

2 4 53 5 6

  C  =

3 0 0−4 6 216   −15   −5

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

16