Last active
October 8, 2022 18:23
-
-
Save ravener/2582e9ca42f193567c9513b0ba1beedb to your computer and use it in GitHub Desktop.
Calculate determinant of an n × n matrix in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Get the submatrix of A | |
# Removing the ii-th row and jj-th column | |
def sub(A, ii, jj): | |
matrix = [] | |
for i in range(len(A)): | |
if i == ii: | |
continue | |
row = A[i].copy() | |
row.pop(jj) | |
matrix.append(row) | |
return matrix | |
def det(A): | |
assert len(A) > 0 | |
assert len(A) == len(A[0]) | |
if len(A) == 1: | |
return A[0][0] | |
value = 0 | |
sign = 1 | |
for j in range(len(A[0])): | |
value += det(sub(A, 0, j)) * A[0][j] * sign | |
# Flip the sign for the next column | |
sign = -sign | |
return value | |
# 3x3 Matrix | |
A = [ | |
[5, 3, 2], | |
[6, 1, 8], | |
[9, 6, 7] | |
] | |
print(det(A)) # => -61 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment