[Python] Matrix determinant

Discussão em 'Python' iniciado por Stack, Dezembro 26, 2024.

  1. Stack

    Stack Membro Participativo

    I have this function to get the determinant of a matrix:

    def determinant(self) -> int:
    """
    Calculates the Determinant of matrix objects.
    Parameters
    ----------
    self
    Returns
    -------
    int
    Example
    -------
    >>> _matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    >>> _matrix = Matrix(_matrix)
    >>> _matrix.determinant()
    0
    """
    if self.row != self.column:
    raise ValueError('Cannot get determinant of this matrix! Must be a square Matrix')
    else:
    def det(matrix):
    row = len(matrix)
    col = len(matrix[0])

    if (row, col) == (1, 1):
    return matrix[0][0]

    # hard coding for 2x2
    elif (row, col) == (2, 2):
    return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]

    # using sarrus method to solve for 3x3, it's a little faster.
    elif (row, col) == (3, 3):
    matrix1 = matrix[:]

    # Extending matrix to use Sarrus Rule.
    for i in range(row - 1):
    _col = []
    for j in range(col):
    _col.append(matrix1[j])
    matrix1.append(_col)

    # Calculating Determinant
    # Adding part
    add_pointers = [(i, i) for i in range(row)]
    result = 0
    for pointer in range(row):
    temp = 1
    for tup in add_pointers:
    i, j = tup
    temp *= matrix1[i + pointer][j]
    result += temp

    # Subtracting part
    sub_pointers = [((row - 1) - i, 0 + i) for i in range(row)]
    for pointers in range(row):
    temp = 1
    for tup in sub_pointers:
    i, j = tup
    temp *= matrix1[i + pointers][j]
    result -= temp
    return result

    else:
    sign = -1
    result = 0
    row1 = [matrix[0] * (sign ** i) for i in range(col)]
    for x, y in enumerate(row1):
    mat = matrix[:][1:]
    sub_matrix = [[mat[j] for j in range(col) if j != x] for i in range(row - 1)]
    result += y * det(sub_matrix)
    return result

    return det(self.matrix)


    I have hard-coded the determinant of a 2x2 and 3x3 matrix, then I'm recusing through the rest for an nxn matrix.

    This is extremely slow. What would be a faster method implemented in pure Python?

    Continue reading...

Compartilhe esta Página