%hide
%auto
def RREF(A):
reduced_echelon_form=True
M = A.nrows()
N = A.ncols()
# if A.det()==0:
# print html("<font size=+1 color=red>Matrix is Singular. Please pick another!</font>")
print html("<font size=+2 color=blue>Using the matrix</font>")
show(A)
global Astart
Astart = copy(A)
# Now, let's start the step by step Gauss-Jordan routine
ROWS = range(M)
COLS = range(N)
PIVOTS = range(min(M,N))
for i in PIVOTS:
# Gauss-Jordan on column i
# First, make the pivot element equal to 1
k = i
# Need to fix this when a column is skipped when finding nonzero pivots
# That is, if the remainder of a column is zero, go on to the next column till you reach the end.
if A[i][i]==0: # swap for non-zero pivot
# start looking in rows below the i-th
while (k<M and A[k][i]==0):
k += 1
if k==M:
print 'All of the remaining rows are zero. Move to next columns or finish.'
else:
A.swap_rows(i,k)
# So, now we should have a non-zero in the pivot position or k=M which means we are done.
# Should consider using the function "nonzero_positions_in_column(i)" and use the min position > i.
# Start zeroing out the rest of column i.
if A[i][i]<>0:
A[i]=A[i]/A[i][i]
if reduced_echelon_form:
for k in ROWS:
if i<>k:
A[k] = A[k]-A[i]*A[k][i]
else:
for k in ROWS:
if i<k:
A[k] = A[k]-A[i]*A[k][i]
print '\n After',i+1,'step(s) the matrix is equivalent to:'
show(A)