Skip to content

More matrix algorithms #745

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 27, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion matrix/matrix_multiplication_addition.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ def add(matrix_a, matrix_b):
matrix_c.append(list_1)
return matrix_c

def scalarMultiply(matrix , n):
return [[x * n for x in row] for row in matrix]

def multiply(matrix_a, matrix_b):
matrix_c = []
Expand All @@ -24,13 +26,50 @@ def multiply(matrix_a, matrix_b):
matrix_c.append(list_1)
return matrix_c

def identity(n):
return [[int(row == column) for column in range(n)] for row in range(n)]

def transpose(matrix):
return map(list , zip(*matrix))

def minor(matrix, row, column):
minor = matrix[:row] + matrix[row + 1:]
minor = [row[:column] + row[column + 1:] for row in minor]
return minor

def determinant(matrix):
if len(matrix) == 1: return matrix[0][0]

res = 0
for x in range(len(matrix)):
res += matrix[0][x] * determinant(minor(matrix , 0 , x)) * (-1) ** x
return res

def inverse(matrix):
det = determinant(matrix)
if det == 0: return None

matrixMinor = [[] for _ in range(len(matrix))]
for i in range(len(matrix)):
for j in range(len(matrix)):
matrixMinor[i].append(determinant(minor(matrix , i , j)))

cofactors = [[x * (-1) ** (row + col) for col, x in enumerate(matrixMinor[row])] for row in range(len(matrix))]
adjugate = transpose(cofactors)
return scalarMultiply(adjugate , 1/det)

def main():
matrix_a = [[12, 10], [3, 9]]
matrix_b = [[3, 4], [7, 4]]
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]

print(add(matrix_a, matrix_b))
print(multiply(matrix_a, matrix_b))

print(identity(5))
print(minor(matrix_c , 1 , 2))
print(determinant(matrix_b))
print(inverse(matrix_d))

if __name__ == '__main__':
main()