Matlab Complete the functions myElimBelow and myElimAbove which are called by th
ID: 3184812 • Letter: M
Question
Matlab Complete the functions myElimBelow and myElimAbove which are called by the function myInv (given). myInv takes a square, invertible matrix and returns its inverse.
1. Augment the matrix A (the example above is shown here) with an identity matrix of the same size
2. Perform the Forward sweep on this augmented matrix. This will be accomplished my myElimBelow.
3. Perform a modified forward sweep again, this time eliminating everything above the diagonal. This will be accomplished by myElimAbove.
4. Divide each row of the augmented matrix by the corresponding diagonal element A(i,i)
5. The augmented portion (columns n+1 through 2*n) is the inverse of A.
Hints myElimBelow 1. Do not use built in Matlab functions. Use nested for-loops. 2. Start with your myForward function. If yours didn't work, get mine from the shared folder (but make sure you understand how it works) 3. Modify it so it doesn't take in b as an argument. 4. Augment the matrix A with an identity matrix of the same size. 5. It's not necessary to worry about sorting rows on each step. 6. Modify it so it only returns an augmented matrix.
Explanation / Answer
matlab code
close all
clear
clc
A = [75.774 17.1187 4.6171 31.7099;
74.3132 70.6046 9.7132 95.0222;
39.2227 3.1833 82.3458 3.4446;
65.5478 27.6923 69.4829 43.8744];
disp('A');
for i=1:size(A,1)
fprintf('%10.5f %10.5f %10.5f %10.5f ',A(i,:));
end
disp(' ');
[~,A_inv] = myInv(A);
disp('A Inverse');
for i=1:size(A,1)
fprintf('%10.5f %10.5f %10.5f %10.5f ',A_inv(i,:));
end
% Function for calculating inverse of a matrix
function [A2,I2] = myInv(A)
I = eye(size(A,1));
[A1,I1] = myElimBelow(A,I);
[A2,I2] = myElimAbove(A1,I1);
for i=1:size(A2,1)
c = A2(i,i);
A2(i,:) = A2(i,:)/c;
I2(i,:) = I2(i,:)/c;
end
end
% Function for obtaining an Upper triangular matrix
function [AA,II] = myElimBelow(A,I)
AA = A;
II = I;
c = 2;
while 1
for i=c:size(A,1)
a = AA(c-1,c-1);
b = AA(i,c-1);
AA(i,:) = AA(i,:)*a-AA(c-1,:)*b;
II(i,:) = II(i,:)*a-II(c-1,:)*b;
end
if c < size(A,1)
c = c+1;
else
break;
end
end
end
% Function for obtaining an Lower triangular matrix
function [AA,II] = myElimAbove(A,I)
AA = A;
II = I;
c = 1;
while 1
for i=1:c
a = AA(c+1,c+1);
b = AA(i,c+1);
AA(i,:) = AA(i,:)*a-AA(c+1,:)*b;
II(i,:) = II(i,:)*a-II(c+1,:)*b;
end
if c < size(A,1)-1
c = c+1;
else
break;
end
end
end
output
A
75.77400 17.11870 4.61710 31.70990
74.31320 70.60460 9.71320 95.02220
39.22270 3.18330 82.34580 3.44460
65.54780 27.69230 69.48290 43.87440
A Inverse
0.02099 0.00386 0.01952 -0.02507
0.00885 0.08178 0.15497 -0.19568
-0.00942 -0.00279 0.00232 0.01266
-0.02203 -0.05298 -0.13065 0.16371