MATLAB: Optimizing using for loops

for loops

Is there a way I can optimize this code using for loops to run in less lines?
function [ determinant, inverse ] = invanddet3by3( A )
%INVANDDET3BY3 Calculates the determinant and the inverse of a 3 X 3 matrix by using
% cofactors and adjoint matrix
a = [A(2,2) A(2,3); A(3,2) A(3,3)];
a11 = invanddet2by2sol( a );
b = [A(2,1) A(2,3); A(3,1) A(3,3)];
a12 = -invanddet2by2sol( b );
c = [A(2,1) A(2,2); A(3,1) A(3,2)];
a13 = invanddet2by2sol( c );
determinant = A(1,1)*a11+A(1,2)*a12+A(1,3)*a13;
d = [A(1,2) A(1,3); A(3,2) A(3,3)];
a21 = -invanddet2by2sol( d );
e = [A(1,1) A(1,3); A(3,1) A(3,3)];
a22 = invanddet2by2sol( e );
f = [A(1,1) A(1,2); A(3,1) A(3,2)];
a23 = -invanddet2by2sol( f );
g = A(1:2,2:3);
a31 = invanddet2by2sol( g );
h = [A(1,1) A(1,3); A(2,1) A(2,3)];
a32 = -invanddet2by2sol( h );
i = A(1:2,1:2);
a33 = invanddet2by2sol( i );
B = [a11 a12 a13; a21 a22 a23; a31 a32 a33];
C = B'
if determinant == 0
inverse = [];
else inverse = C.*1/determinant;
end
The brief was to do this:
Create a function that calculates the determinant and the inverse of a generic 3 X 3 matrix with the method of the cofactors and the adjoint matrix
It's been recommended on my course to use for loops but i'm not sure how to do it. Thanks!

Best Answer

[r c] = size(a);
m = ones(r,c);
a_temp=a;
for i = 1:r
for k = 1:c
a_temp([i],:)=[];
a_temp(:,[k])=[];
m(i,k) = ((-1)^(i+k))*det(a_temp);
a_temp=a;
end
end
inverse=m.*1/det(a)