Sunday, August 27, 2023

Calculate inverse matrix 2x2 and n dimension

 




















Result in simulation python


Source code 

# Function to calculate the transpose of a matrix
def calculate_transpose(matrix):
    # Determine the number of rows and columns in the matrix
    rows = len(matrix)
    columns = len(matrix[0])

    # Initialize the transposed matrix
    transposed_matrix = [[0] * rows for _ in range(columns)]

    # Iterate over the rows of the original matrix
    for i in range(rows):
        # Iterate over the columns of the original matrix
        for j in range(columns):
            # Assign the value from the original matrix to the transposed matrix
            transposed_matrix[j][i] = matrix[i][j]

    return transposed_matrix


# Function to calculate the determinant of a matrix
def calculate_determinant(matrix):
    # Base case for 2x2 matrix
    if len(matrix) == 2:
        determinant = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
        return determinant

    det = 0
    for c in range(len(matrix)):
        sign = (-1) ** c
        sub_matrix = [row[:c] + row[c+1:] for row in matrix[1:]]
        sub_det = calculate_determinant(sub_matrix)
        det += sign * matrix[0][c] * sub_det

    return det


# Function to calculate the matrix of minors
def calculate_matrix_of_minors(matrix):
    minors = []
    n = len(matrix)

    for i in range(n):
        row = []
        for j in range(n):
            submatrix = [row[:j] + row[j+1:] for row in (matrix[:i] + matrix[i+1:])]
            minor = calculate_determinant(submatrix)
            row.append(minor)
        minors.append(row)

    return minors


# Function to calculate the matrix of cofactors
def calculate_matrix_of_cofactors(matrix):
    cofactors = []
    n = len(matrix)

    for i in range(n):
        row = []
        for j in range(n):
            cofactor = (-1) ** (i + j) * matrix[i][j]
            row.append(cofactor)
        cofactors.append(row)

    return cofactors


# Function to calculate the inverse of an n x n matrix
def calculate_inverse(matrix):
    n = len(matrix)
    determinant = calculate_determinant(matrix)

    if determinant == 0:
        raise ValueError("The matrix has no inverse.")

    minors = calculate_matrix_of_minors(matrix)
    cofactors = calculate_matrix_of_cofactors(minors)
    adjugate = calculate_transpose(cofactors)

    inverse_matrix = [[adjugate[i][j] / determinant for j in range(n)] for i in range(n)]
    return inverse_matrix


# Function to display a matrix
def display(matrix):
    for row in matrix:
        print(" ".join(str(num) for num in row))


# Function to enter a matrix from user input
def enter_matrix():
    dimension = int(input("Enter the dimension of the matrix: "))

    matrix = []
    for i in range(dimension):
        row = []
        for j in range(dimension):
            while True:
                try:
                    element = int(input(f"Enter element at position a{i+1}{j+1}: "))
                    break
                except ValueError:
                    print("Invalid input. Please enter a numeric value.")
            row.append(element)
        matrix.append(row)

    return matrix


while True:
    try:
        matrix = enter_matrix()

        print("\nMatrix:")
        display(matrix)

        print("\nTranspose Matrix:")
        transpose_matrix = calculate_transpose(matrix)
        display(transpose_matrix)
        determinant = calculate_determinant(matrix)
        print("\nDeterminant:", determinant)
        print("\nInverse Matrix:")
        if len(matrix) >= 2:  
            inverse_matrix = calculate_inverse(matrix)
            display(inverse_matrix)
        else:
            print("Inverse calculation is supported only for matrices larger than or equal to 2x2.")

    except ValueError as e:
        print(str(e))


Share:

0 comments:

Post a Comment