Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

2.11. The inverse of a matrix A can be defined as the matrix X whose columns x j

ID: 642963 • Letter: 2

Question

2.11. The inverse of a matrix A can be defined as the matrix X whose columns x j solve the equations Ax j = e j, where ej is the jth column of the identity matrix. (a) Starting with the function bslashtx, write a MATLAB function X = myinv(A) that computes the inverse of A. Your function should call lutx only once and should not use the built-in MATLAB backslash operator or mv function. (b) Test your function by comparing the inverses it computes with the inverses obtained from the built-in mv(A) on a few test matrices.

Explanation / Answer


function b = myinv(a)
% Find dimensions of input matrix
[r,c] = size(a);

% If input matrix is not square, stop function
if r ~= c
disp('Only Square Matrices, please')
b = [];
return
end

% Target identity matrix to be transformed into the output
% inverse matrix
b = eye(r);

%The following code actually performs the matrix inversion by working
% on each element of the input
for j = 1 : r
for i = j : r
if a(i,j) ~= 0
for k = 1 : r
s = a(j,k); a(j,k) = a(i,k); a(i,k) = s;
s = b(j,k); b(j,k) = b(i,k); b(i,k) = s;
end
t = 1/a(j,j);
for k = 1 : r
a(j,k) = t * a(j,k);
b(j,k) = t * b(j,k);
end
for L = 1 : r
if L ~= j
t = -a(L,j);
for k = 1 : r
a(L,k) = a(L,k) + t * a(j,k);
b(L,k) = b(L,k) + t * b(j,k);
end
end
end
end
break
end
% Display warning if a row full of zeros is found
if a(i,j) == 0
disp('Warning: Singular Matrix')
b = 'error';
return
end
end
% Show the evolution of the input matrix, so that we can
% confirm that it became an identity matrix.

% Testing Now
% Input matrix
a = [3 5 -1 -4
1 4 -.7 -3
0 -2 0 1
-2 6 0 .3];

% Call the function to find its inverse
b = myinv(a)

% Compare with a result generated by Matlab
c = inv(a)