MATLAB: Gauss-Jordan Elimination

gauss jordan eliminationMATLABmatrix

So I have code for solving certain aspects of performing a Gauss-Jordan Elimination:
function s = search(M,i)
[x, y] = size(M); %x is rows, y is columns
submatrix = M([i:x],[1:y]); %output is rows below and equal to i
column_index = any(submatrix,1); %gives logical array
s = find(column_index,1); %gives column index
end
function m = move(M,i,j)
[x, y] = size(M); %x is rows and y is columns


submatrix = M([i:x],[1:y]); %creates submatrix of ith row down
column_j = submatrix(:,j); %gives jth column
row = find(column_j,1); %gives row number of first nonzero
i_row = M(i,:); %gives ith row of M
row_zero = M(row+1,:); %gives row that has nonzero in M
M(i,:) = row_zero;
M(row+1,:) = i_row
end
function n = normalize(M,i,j)
[x,y] = size(M); %x is rows and y is columns
element = M(i,j); %gives (i,j)th element
row_i = M(i,:); %gives ith row

div = row_i/element; %divides ith row by element
M(i,:) = div
end
function r = reduce(M,i,j,k)
[x,y] = size(M); %x is rows and y is columns
row_i = M(i,:); %gives ith row
row_k = M(k,:); %gives kth row
row_ik = row_i.*row_k; %multiplies rows i and k
new = row_k-row_ik; %makes jth position 0
M(k,:) = new %puts reduced row in kth position
end
Now I'm trying to use these four functions in order to create a step-by-step process of reducing a matrix (of any size) using for-loop from the 1st row to the last row of the matrix.
From what I understand, I have to use search(M,i) to find the first nonzero column, then if M(i,j) = 0 use move(M,i,j) to change the pivotal entry to a nonzero, if that pivotal entry is instead nonzero, use normalize(M,i,j) to make the initial element of that row 1, then use reduce(M,i,j,k) to make every other nonzero in that column 0. And repeat this process.
I have this code started:
function GJE = GJ(M)
[x, y] = size(M);
z = search(M,x); %finds first nonzero column
for i=z;j=1;k=1;
if M(i,j) == 0
move(M,i,j)
else
normalize(M,i,j)
end %of if
end %of for
end %of function
which seems to work for moving some rows around, but I'm lost after this, especially on how to make it for any sized matrix.
This is my example matrix:
M = [0 0 2 -4 1 7 -2;0 0 1 -2 0 4 0;1 3 2 -4 1 10 -3;2 6 1 -2 0 10 -2]

Best Answer

I didn't use the (sub-)functions, but tried to sketch out the algorithm following your logic in this file:
I have tested it and compared the results with the built-in function rref().
Hope this helps. Please let me know how it goes.
Related Question