Using recursive method for finding the determinant of a matrix

15 ビュー (過去 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 Center および File ExchangeMATLAB についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by