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

Result for used naming:
a00 * (a11*a22*a33 + a12*a23*a31 + a13*a21*a32 - a31*a22*a13 - a32*a23*a11 - a33*a21*a12) -
a10 * (a01*a22*a33 + a02*a23*a31 + a03*a21*a32 - a31*a22*a03 - a32*a23*a01 - a33*a21*a02) +
a20 * (a01*a12*a33 + a02*a13*a31 + a03*a11*a32 - a31*a12*a03 - a32*a13*a01 - a33*a11*a02) -
a30 * (a01*a12*a23 + a02*a13*a21 + a03*a11*a22 - a21*a12*a03 - a22*a13*a01 - a23*a11*a02)

@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