rref of a rectangular matrix in micropython in python

To find the reduced row echelon form (rref) of a rectangular matrix in MicroPython, you can implement the Gaussian elimination algorithm:

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

    for pivot in range(num_rows):
        # Find the row with the largest absolute value for the pivot column
        max_row = pivot
        for j in range(pivot + 1, num_rows):
            if abs(matrix[j][pivot]) > abs(matrix[max_row][pivot]):
                max_row = j

        # Swap the rows
        matrix[pivot], matrix[max_row] = matrix[max_row], matrix[pivot]

        # Scale the pivot row to make the pivot element 1
        pivot_elem = matrix[pivot][pivot]
        matrix[pivot] = [elem / pivot_elem for elem in matrix[pivot]]

        # Eliminate other rows using the pivot row
        for i in range(num_rows):
            if i != pivot:
                factor = matrix[i][pivot]
                matrix[i] = [elem - factor * matrix[pivot][col] for col, elem in enumerate(matrix[i])]

    return matrix
896 chars
26 lines

You can call this function by passing your rectangular matrix as a list of lists. Each inner list represents a row in the matrix. Here's an example:

main.py
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

rref_matrix = rref(matrix)
print(rref_matrix)
110 chars
7 lines

This will output the reduced row echelon form of the given matrix:

main.py
[[1.0, 0.0, -1.0],
 [0.0, 1.0, 2.0],
 [0.0, 0.0, 0.0]]
55 chars
4 lines

Note: This implementation assumes that the given matrix is non-singular and has a unique solution.

gistlibby LogSnag