You are on page 1of 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
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.




−4
(d) Enter the column vector w =  0 .
6

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

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

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

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

(i) Compute the vector u where [uj ] = [vj wj ] (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
Matrix Operations: Transposes and Inverses.
 
2 3 5
(a) Enter the matrix A =  5 1 8  (type A=[2, 3, 5; 5, 1, 8; 12, 5, 21]).
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) .


 
2 5 1
(e) Enter the matrix C =  3 1 5 
5 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
Matrix Operations: Gaussian Elimination.
 
2 3 5
(a) Enter the matrix A =  5 1 8 
12 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 performing
the 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 its
original value by typing B = H before using the rref command).
 
2 5 1
(h) Enter the matrix C =  3 1 5 
5 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 −1 v.

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 new
M-file, type the word edit at the MATLAB command prompt. The MATLAB editor
will 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. MATLAB
ignores 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 find
later. 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 Bar
of the MATLAB editor.

(e) Hit the ENTER key twice and the TAB key once. Determine the number of rows in
the input matrix A by typing n = size(A,1). Hit the ENTER key once. Determine
the 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 6= m, we need to exit with an error message. Hit the ENTER key once. Type the
following:

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 the
same size as A.

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

These commands tell MATLAB that we are creating two loops. The outer loop is for
the 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 by
deleting its ith row. Type the following:

5
% 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 tells
MATLAB 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, keep
rows 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 jth column of M using similar code. Hit
the 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 ENTER
key 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 which
is the TRANSPOSE of the adjoint. Hit the ENTER key once. Type the following:
adjA = adjA’

6
(o) Hit the ENTER once and the BACKSPACE key 4 times. To close the very first
if-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 the
box to change to the directory where you saved the file find adjoint.m. To check that
you have the correct directory, type pwd.
 
2 3 5
(q) Enter the matrix A =  5 1 8 .
12 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
Cramer’s Rule.

(a) We are going to create a new M-file. If the MATLAB editor is still open, select the
New 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). Provide
a line-by-line interpretation of the code cramers rule.m.
 
1 4 5
(e) Return to the MATLAB command window. Enter the matrix A =  4 2 5 
−3 3 −1

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

8
(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
     
1 3 −2 0 2 1 2/3 1/3 2/3
R= 3 0 5  and S =  −2 0 −4  T =  −2/3 2/3 1/3 
−2 5 4 −1 4 0 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/or
orthogonal.
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
Test the code on the following matrices:
     
3 1 5 0 9 −12 1 0 0
A= 1 0 −7  and B =  −9 0 20  C= 0 1 0 
5 −7 9 12 −20 0 0 0 1

Even if a square matrix is neither symmetric nor skew-symmetric, it can be decomposed as


the 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 as
the sum of a symmetric matrix and a skew-symmetric matrix. The code should print
A1 and A2 or return an error message if A is not square. Include your code when you
turn in the project.

(d) Test your code on the following matrices:


   
3 12 0 1 0 1
U =  1 −5 1  and V =  2 −1 0 
9 1 8 4 0 6

10
Vector Spaces.
 
−4 0 −4 3
(a) Enter the matrix A =
−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. To
do this, we solve Bc = x so we need to row reduce the augmented matrix [B x]. Type
aug = [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 by
typing 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
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 the
following vectors: v1 = (1, 3, −1, 2), v2 = (0, −4, 5, 1), v3 = (−7, 2, 1, 0). Create the
matrix 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
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 find
the 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 and
m = 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
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.


 
2 3 5
A= 5 1 8 
12 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 use
the expression
xT Ax
,
xT x
which called the Rayleigh-Ritz ratio, to estimate the value of the smallest and largest eigen-
values of A:
xT Ax
λmin = min = min xT Ax (1)
x6=0 xT x xT x=1
xT Ax
λmax = max T = max xT Ax (2)
x6=0 x x xT x=1

(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
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 lookup
any functions with which you are not familiar.)

15
(c) Test the code on the following matrices
     
8 1 1 1 2 3 3 0 0
A= 1 8 1  B= 2 4 5  C =  −4 6 2 
1 1 8 3 5 6 16 −15 −5

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

16

You might also like