Skip to content

Instantly share code, notes, and snippets.

@vagran
Last active March 14, 2018 11:02
Show Gist options
  • Save vagran/5ad38c3154b086954012ebce3ce1a37d to your computer and use it in GitHub Desktop.
Save vagran/5ad38c3154b086954012ebce3ce1a37d to your computer and use it in GitHub Desktop.
Get determinant expression for a 4x4 matrix
# Get determinant expression for a matrix.
# Works for 4x4 matrix only because Rule of Sarrus is used. Can be adapted for any size by using
# recursive algorithm.
M = []
SIZE = 4
def Minor(rowIdx):
"""
:param rowIdx: Row index for minor submatrix. Assuming column 0.
:return: Minor submatrix.
"""
m = []
for i in range(0, SIZE):
if i == rowIdx:
continue
row = [M[i][j] for j in range(1, SIZE)]
m.append(row)
return m
def MinorDet(m):
"""
:param m: Minor submatrix.
:return: Expression of minor determinant, defined by Rule of Sarrus.
"""
return (m[0][0] + "*" + m[1][1] + "*" + m[2][2] + " + " +
m[0][1] + "*" + m[1][2] + "*" + m[2][0] + " + " +
m[0][2] + "*" + m[1][0] + "*" + m[2][1] + " - " +
m[2][0] + "*" + m[1][1] + "*" + m[0][2] + " - " +
m[2][1] + "*" + m[1][2] + "*" + m[0][0] + " - " +
m[2][2] + "*" + m[1][0] + "*" + m[0][1])
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(M[0][0] + " * (" + MinorDet(Minor(0)) + ") -\n" +
M[1][0] + " * (" + MinorDet(Minor(1)) + ") +\n" +
M[2][0] + " * (" + MinorDet(Minor(2)) + ") -\n" +
M[3][0] + " * (" + MinorDet(Minor(3)) + ")\n")
@vagran
Copy link
Author

vagran commented Mar 14, 2018

Use with caution since such operations order may lose precision. Check this variant for more safe solution: https://gist.github.com/vagran/385b5df652d3401b544a231c09abbece

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment