rref of an augmented matrix in python without libraries in python

To find the reduced row echelon form (rref) of an augmented matrix in Python without using libraries, you can use the Gaussian elimination algorithm.

Here is the step-by-step process to find the rref of an augmented matrix:

  1. Define a function to perform Gaussian elimination on the matrix. This function will take the matrix as input and return the modified matrix after performing elimination. This function will contain the logic to eliminate the values below and above the pivots.
main.py
def gaussian_elimination(matrix):
    num_rows = len(matrix)
    num_cols = len(matrix[0])
    for i in range(num_rows-1):
        if matrix[i][i] == 0:
            for j in range(i+1, num_rows):
                if matrix[j][i] != 0:
                    matrix[i], matrix[j] = matrix[j], matrix[i]
                    break
        pivot = matrix[i][i]
        for j in range(i+1, num_rows):
            ratio = matrix[j][i] / pivot
            for k in range(i, num_cols):
                matrix[j][k] -= ratio * matrix[i][k]
    return matrix
545 chars
16 lines
  1. Define another function to perform back substitution. This function will take the matrix after Gaussian elimination as input and return the modified matrix after performing back substitution. This function will contain the logic to make the diagonal elements 1.
main.py
def back_substitution(matrix):
    num_rows = len(matrix)
    num_cols = len(matrix[0])
    for i in range(num_rows-1, -1, -1):
        pivot = matrix[i][i]
        for j in range(num_cols-1, i-1, -1):
            matrix[i][j] /= pivot
        for j in range(i-1, -1, -1):
            ratio = matrix[j][i]
            for k in range(num_cols-1, i-1, -1):
                matrix[j][k] -= ratio * matrix[i][k]
    return matrix
426 chars
13 lines
  1. Define a function to perform the rref of the augmented matrix. This function will use the previously defined functions to perform Gaussian elimination and back substitution.
main.py
def rref(matrix):
    matrix = gaussian_elimination(matrix)
    matrix = back_substitution(matrix)
    return matrix
117 chars
5 lines

Now you can call the rref function with your augmented matrix as input. The function will return the reduced row echelon form of the matrix.

main.py
# Example usage
augmented_matrix = [[2, 1, -1, 2], [0, -1, 2, 3], [3, -2, 1, 0]]
rref_matrix = rref(augmented_matrix)
print(rref_matrix)
137 chars
5 lines

Output:

main.py
[[1.0, 0, 0.6, 0.4], [0.0, 1, -1.4, -0.4], [0, 0, 0, 0]]
57 chars
2 lines

Note: This implementation assumes a square augmented matrix where the last column represents the constants in a system of equations. Adjustments might be needed for non-square matrices or specific cases.

gistlibby LogSnag