In: Computer Science
Make the following matlab function.
D=inverses(A)
It takes the input of an nxn matrixA.
First, the function has to determine whether A is invertible (you may want to use the function rank to do that). If A is not invertible, the function has to return an empty matrix D=[ ]; and terminates with a message “Matrix A is not invertible”.
If A is invertible, then the function reduces the matrix [A eye(n)] into the reduced echelon form and returns the matrix D that is the inverse of the matrix A. You can use a MATLAB built-in function rref for this part.
%matlab code
function D = inverse(A)
[n n] = size(A);
% Singular matrix found
if det(A) == 0
disp('Matrix A is not invertible')
D = [];
quit
end
D = eye(n);
%matrix inversion
for j = 1 : n
for i = j : n
if A(i,j) != 0
for t = 1 : n
suD = A(j,t);
A(j,t) = A(i,t);
A(i,t) = suD;
suD = D(j,t);
D(j,t) = D(i,t);
D(i,t) = suD;
end
temp = 1/A(j,j);
for t = 1 : n
A(j,t) = temp * A(j,t);
D(j,t) = temp * D(j,t);
end
for idx = 1 : n
if idx != j
temp = -1*A(idx,j);
for k = 1 : n
A(idx,t) = A(idx,t) + temp * A(j,t);
D(idx,t) = D(idx,t) + temp * D(j,t);
end
end
end
end
break
end
end
end
n = input("Enter size of matrix n: ");
A = zeros(n,n);
for i=1:n
for j=1:n
A(i,j) = input("ENter matrix value: ");
end
end
D = inverse(A)
%{
output:
Enter size of matrix n: 3
ENter matrix value: 1
ENter matrix value: 2
ENter matrix value: 3
ENter matrix value: 4
ENter matrix value: 5
ENter matrix value: 6
ENter matrix value: 7
ENter matrix value: 8
ENter matrix value: 9
D =
1.00000 0.00000 -1.30000
0.00000 0.20000 0.20000
0.00000 0.00000 0.01111
%}