Wednesday, August 30, 2023

Calculate Determinant matrix with n dimension user input




Result in python code













2. Source code 

def calculate_determinant(matrix):

    dimension = len(matrix)

    if dimension == 1:

        return matrix[0][0]

    determinant = 0

    for col in range(dimension):

        sub_matrix = [[0] * (dimension - 1) for _ in range(dimension - 1)]

        for i in range(1, dimension):

            curr_col = 0

            for j in range(dimension):

                if j != col:

                    sub_matrix[i - 1][curr_col] = matrix[i][j]

                    curr_col += 1

        sub_determinant = calculate_determinant(sub_matrix)

        determinant += ((-1) ** col) * matrix[0][col] * sub_determinant

    return determinant

while True:

    try:

        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)

        print("\nMatrix:")

        for row in matrix:

            print(" ".join(str(num) for num in row))

        determinant = calculate_determinant(matrix)

        print("\nDeterminant:", determinant)

    except ValueError:

        print("Invalid matrix input. Please enter numeric values only.")

Share:

0 comments:

Post a Comment