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

Matlab practice

Embed Size (px)

DESCRIPTION

Show important commands demo by Zunaib Ali uet ATD Campus

Citation preview

Page 1: Matlab practice

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

Page 2: Matlab practice

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: Matlab practice

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: Matlab practice

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: Matlab practice

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: Matlab practice

% 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: Matlab practice

(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: Matlab practice

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: Matlab practice

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

9

Page 10: Matlab practice

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

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

10

Page 11: Matlab practice

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

Page 12: Matlab practice

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

12

Page 13: Matlab practice

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

Page 14: Matlab practice

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

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’);

14

Page 15: Matlab practice

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;

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

Page 16: Matlab practice

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

16