write matrix solve 5x4 algorithm without numpy and scipy in python

main.py
def matrix_multiply(matrix1, matrix2):
    result = [[0 for _ in range(len(matrix2[0]))] for _ in range(len(matrix1))]
    
    for i in range(len(matrix1)):
        for j in range(len(matrix2[0])):
            for k in range(len(matrix2)):
                result[i][j] += matrix1[i][k] * matrix2[k][j]
    
    return result

def gauss_elimination(matrix):
    for i in range(len(matrix)):
        # Partial pivoting
        max_row = max(range(i, len(matrix)), key=lambda x: abs(matrix[x][i]))
        matrix[i], matrix[max_row] = matrix[max_row], matrix[i]
        
        if matrix[i][i] == 0:
            raise ValueError("Matrix is singular")
        
        for j in range(i+1, len(matrix)):
            factor = matrix[j][i] / matrix[i][i]
            for k in range(i, len(matrix)+1):
                matrix[j][k] -= factor * matrix[i][k]
    
    # Back substitution
    result = [0 for _ in range(len(matrix))]
    for i in range(len(matrix) - 1, -1, -1):
        result[i] = matrix[i][len(matrix)] / matrix[i][i]
        for j in range(i-1, -1, -1):
            matrix[j][len(matrix)] -= matrix[j][i] * result[i]
            
    return result

def solve_5x4(matrix):
    coefficients_matrix = [row[:4] for row in matrix]
    constants_vector = [row[4] for row in matrix]
    
    coefficients_matrix = gauss_elimination(coefficients_matrix)
    
    return coefficients_matrix

matrix = [
    [4, 5, 7, 9, 12],
    [3, 8, 6, 4, 10],
    [5, 6, 4, 7, 11],
    [3, 6, 9, 2, 9],
    [7, 5, 8, 7, 14]
]

print(solve_5x4(matrix))
1540 chars
51 lines

related categories

gistlibby LogSnag