Created
March 14, 2018 11:00
-
-
Save vagran/385b5df652d3401b544a231c09abbece to your computer and use it in GitHub Desktop.
Get determinant expression for matrix of arbitrary size.
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 determinant expression for a matrix. | |
def Minor(M, rowIdx): | |
""" | |
:param M Matrix to get minor for. | |
:param rowIdx: Row index for minor submatrix. Assuming column 0. | |
:return: Minor submatrix. | |
""" | |
m = [] | |
for i in range(0, len(M)): | |
if i == rowIdx: | |
continue | |
row = [M[i][j] for j in range(1, len(M))] | |
m.append(row) | |
return m | |
def DetExpr(m): | |
""" | |
:param m: Minor submatrix. | |
:return: Expression of minor determinant | |
""" | |
if len(m) == 1: | |
return m[0][0] | |
res = "(" | |
for i in range(0, len(m)): | |
if i % 2 == 1: | |
res += " - " | |
elif i > 1: | |
res += " + " | |
res += m[i][0] + "*" + DetExpr(Minor(m, i)) | |
res += ")" | |
return res | |
M = [] | |
SIZE = 4 | |
for i in range(0, SIZE): | |
# Members naming is defined here | |
row = ["a" + str(i) + str(j) for j in range(0, SIZE)] | |
M.append(row) | |
print(DetExpr(M)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output for 4x4 matrix:
(a00*(a11*(a22*a33 - a32*a23) - a21*(a12*a33 - a32*a13) + a31*(a12*a23 - a22*a13)) - a10*(a01*(a22*a33 - a32*a23) - a21*(a02*a33 - a32*a03) + a31*(a02*a23 - a22*a03)) + a20*(a01*(a12*a33 - a32*a13) - a11*(a02*a33 - a32*a03) + a31*(a02*a13 - a12*a03)) - a30*(a01*(a12*a23 - a22*a13) - a11*(a02*a23 - a22*a03) + a21*(a02*a13 - a12*a03)))