Greetings,
I am working on an assignment where I am required to write an algorithm that can find the determinant of an nxn matrix using row reduction. The algorithm I've currently written will try to get the matrix in upper triangular form, then multiply all diagonal rows:
A = input("Please enter matrix: ") disp("Given Matrix: ")disp(A)s = length(A{i});% Make sure matrix is nxn
if(size(A,1) == size(A,2)) % Get matrix in upper triangular form
for m = 1:(s)-1 for n = s:-1:m+1 %If diagonal is 0, add nonzero row to it%
if A(m,m) == 0 disp("diagonal 0 found. ") A(m,:) = A(m,:) + A(n,:); % Add nonzero row to avoid divide by 0
end r = A(n,m)/A(m,m); A(n,:) = A(n,:) - r*A(m,:); % Reduce row
end end disp("Reduced Upper Triangular form: ") disp(A) % Multiply main diagonal together
D = 1; for x = 1:s D = D * A(x,x); end disp("Determinant: " + D) disp("================================================================")else disp("ERROR: Matrix is not nxn in size.")end
My current issue I've been struggling with is when a diagonal entry is 0. For example, let's say the inputted matrix is as follows:
A = [0 -9 -18 -2.5; 2 -2.5 -3 0; 3 0 3 -1; 3 0 3 0]
In this case, the first entry is 0. Obviously we can't divide by zero, so before row reduction can occur I add an arbitrary row. In my code, I add the bottomost row, so this turns that entry nonzero. But I realize this solution is completely non-dynamic, and doesn't possibly account for every case where a diagonal entry could be zero. So I'm looking for some help finding the best solution to fix this issue. I was thinking I could iterate through every row until I find one where column m is nonzero, then add that to the currently indexed row, but then I run into the issue of turning entries that were previously 0 to nonzero entries, so that is something I need to also be checking as well. Any advice on this issue would be greatly appreciated.
Best Answer