Using recursive method for finding the determinant of a matrix

조회 수: 16 (최근 30일)
Junseo Woo
Junseo Woo 2020년 6월 11일
댓글: Junseo Woo 2020년 6월 13일
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

채택된 답변

Voss
Voss 2020년 6월 12일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by