MATLAB: How to properly account for zeros during row reduction

linear algebramatrix manipulation

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

As you go through reducing rows, after a reduction, all the rows below your current row will now be zero to the left of their diagonal.
So when you go on to the next row, if it has zero along the diagonal, search for the first row below that which has a non-zero in that column, and exchange that row with the current row, and then do the reduction.
This cannot introduce non-zeros to the left because you can be sure that all entries to the left of your current column will be zero due to the reduction process.
This could end up swapping a non-zero to the left of a diagonal on something below your current row, but that does not matter: that will be cleared up as you do further reductions
0 8 3 7 2 %did this one already
0 0 0 5 3 %swap

0 2 1 5 7 %swap
0 0 7 8 1
After this swap and you reduce the second row, you will end up having to swap the (now) third row and the 4th row... but that's fine.