Last active
March 14, 2018 11:02
-
-
Save vagran/5ad38c3154b086954012ebce3ce1a37d to your computer and use it in GitHub Desktop.
Get determinant expression for a 4x4 matrix
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. | |
# 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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use with caution since such operations order may lose precision. Check this variant for more safe solution: https://gist.github.com/vagran/385b5df652d3401b544a231c09abbece