[go: up one dir, main page]

0% found this document useful (0 votes)
3 views2 pages

Code Part Matlab

Uploaded by

Soumya Chandrika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Code Part Matlab

Uploaded by

Soumya Chandrika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

% 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);

You might also like