Clear Filters
Clear Filters

Using recursive method for finding the determinant of a matrix

40 views (last 30 days)
Hello, I'd like to find the determinant of a matrix without using built-in functions.
I thought of using cofactor expansion, and this is my code.
(I'm very new to this MATLAB programming, and I have very little knowledge about this part.)
I'm actually not sure if I could arrange the codes like that.
I could really use some help, please. Thank you for reading.
function det=myDet(A)
if size(A)==[2 2]
a_ij=A(i, j);
det=(a_11)*(a_22)-(a_12)*(a_21);
else
i=1:n;
A(:,1)=[];
A(i,:)=[];
A=A_i;
det=symsum((((-1)^(i+1))*myDet(A_i)),i,1,n)
end
end

Accepted Answer

Voss
Voss on 12 Jun 2020
It looks like what you have in mind could be implemented like this:
function det = myDet(A)
if isequal(size(A),[2 2])
det = A(1,1)*A(2,2)-A(1,2)*A(2,1);
else
det = 0;
top_row = A(1,:);
A(1,:) = [];
for i = 1:size(A,2)
A_i = A;
A_i(:,i) = [];
det = det+(-1)^(i+1)*top_row(i)*myDet(A_i);
end
end
end
But note that there is nothing special about the 2-by-2 case, so you could let the recursion go all the way down to the scalar case:
function det = myDet(A)
if isscalar(A)
det = A;
return
end
det = 0;
top_row = A(1,:);
A(1,:) = [];
for i = 1:size(A,2)
A_i = A;
A_i(:,i) = [];
det = det+(-1)^(i+1)*top_row(i)*myDet(A_i);
end
end

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!