rref of a rectangular matrix in python without libraries in python

To compute the reduced row echelon form (RREF) of a rectangular matrix in Python without using any libraries, you can use the following code:

main.py
def rref(matrix):
    num_rows = len(matrix)
    num_cols = len(matrix[0])

    lead = 0
    for r in range(num_rows):
        if lead >= num_cols:
            return matrix

        pivot_row = r
        while matrix[pivot_row][lead] == 0:
            pivot_row += 1

            if pivot_row == num_rows:
                pivot_row = r
                lead += 1
                if num_cols == lead:
                    return matrix

        matrix[pivot_row], matrix[r] = matrix[r], matrix[pivot_row]

        if matrix[r][lead] != 0:
            scalar = matrix[r][lead]
            matrix[r] = [entry / scalar for entry in matrix[r]]

        for i in range(num_rows):
            if i != r:
                scalar = matrix[i][lead]
                matrix[i] = [entry - scalar * matrix[r][j] for j, entry in enumerate(matrix[i])]

        lead += 1

    return matrix

# Example usage
example_matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

result = rref(example_matrix)
print(result)
999 chars
44 lines

The rref function takes a matrix as input and returns its reduced row echelon form. It uses Gaussian elimination with pivoting to transform the matrix into RREF. The function iterates over the rows of the matrix, pivoting if necessary to ensure that the lead entry (the leftmost non-zero entry) of each row is equal to 1. It then eliminates all other entries in the same column by subtracting multiples of the pivot row from them. Finally, the lead is incremented to move to the next column.

Note that this implementation assumes that the input matrix is a list of lists, where each inner list represents a row of the matrix. The example usage demonstrates how to use the rref function with an example matrix and prints the resulting RREF.

gistlibby LogSnag