Using recursive method for finding the determinant of a matrix
15 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 个)
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!