rref of an augmented matrix without using numpy in python

Here is one way to compute the Reduced Row Echelon Form (RREF) of an augmented matrix in Python, without using numpy:

main.py
def rref(matrix):
    lead = 0
    rowCount = len(matrix)
    columnCount = len(matrix[0])
    for r in range(rowCount):
        if lead >= columnCount:
            return
        i = r
        while matrix[i][lead] == 0:
            i += 1
            if i == rowCount:
                i = r
                lead += 1
                if columnCount == lead:
                    return
        matrix[i], matrix[r] = matrix[r], matrix[i]
        lv = matrix[r][lead]
        matrix[r] = [mrx / float(lv) for mrx in matrix[r]]
        for i in range(rowCount):
            if i != r:
                lv = matrix[i][lead]
                matrix[i] = [iv - lv*rv for rv,iv in zip(matrix[r],matrix[i])]
        lead += 1
    return matrix
735 chars
25 lines

The rref function takes a matrix in the form of a list of lists (each inner list representing a row), and returns the matrix in RREF form.

This implementation of Gaussian Elimination algorithm uses partial pivoting to find the maximum coefficient in the column as the pivot for the elimination. Then, it performs the elimination to arrive at the RREF form.

gistlibby LogSnag