% experiment 1
% (a) Finding the inverse of a n X n sqaure matrix without
% using inbuilt command
% (b) Comparing it with the inbuit command
function A_inv = inverse_by_adjoint(A)
[n, m] = size(A);
% Check if square
if n ~= m
error('Matrix must be square');
end
% Calculate determinant
detA = determinant(A);
if detA == 0
error('Matrix is singular and not invertible');
end
% Calculate cofactor matrix
Cof = zeros(n);
for i = 1:n
for j = 1:n
minor = A;
minor(i,:) = [];
minor(:,j) = [];
Cof(i,j) = (-1)^(i+j) * determinant(minor);
end
end
% Adjoint is transpose of cofactor
Adj = Cof';
% Inverse = (1/det) * adjoint
A_inv = (1/detA) * Adj;
end
function d = determinant(A)
[n, ~] = size(A);
if n == 1
d = A(1,1);
elseif n == 2
d = A(1,1)*A(2,2) - A(1,2)*A(2,1);
else
d = 0;
for j = 1:n
minor = A;
minor(1,:) = [];
minor(:,j) = [];
d = d + (-1)^(1+j) * A(1,j) * determinant(minor);
end
end
end
%EXAMPLE testing without inv function {by using above code calling the function}
A=[4,3;3,2];
A_inv=inverse_by_adjoint(A);
disp(A_inv);
%EXAMPLE testing with inv function
A=[4,3;3,2];
A_inv = inv(A);
disp('Inverse of A is:');
disp(A_inv);