Skip to content

Commit 441b82a

Browse files
RayCursepoyea
authored andcommitted
More matrix algorithms (TheAlgorithms#745)
* added matrix minor * added matrix determinant * added inverse,scalar multiply, identity, transpose
1 parent 8b8a6d8 commit 441b82a

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

matrix/matrix_multiplication_addition.py

+40-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ def add(matrix_a, matrix_b):
1010
matrix_c.append(list_1)
1111
return matrix_c
1212

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

1416
def multiply(matrix_a, matrix_b):
1517
matrix_c = []
@@ -24,13 +26,50 @@ def multiply(matrix_a, matrix_b):
2426
matrix_c.append(list_1)
2527
return matrix_c
2628

29+
def identity(n):
30+
return [[int(row == column) for column in range(n)] for row in range(n)]
31+
32+
def transpose(matrix):
33+
return map(list , zip(*matrix))
34+
35+
def minor(matrix, row, column):
36+
minor = matrix[:row] + matrix[row + 1:]
37+
minor = [row[:column] + row[column + 1:] for row in minor]
38+
return minor
39+
40+
def determinant(matrix):
41+
if len(matrix) == 1: return matrix[0][0]
42+
43+
res = 0
44+
for x in range(len(matrix)):
45+
res += matrix[0][x] * determinant(minor(matrix , 0 , x)) * (-1) ** x
46+
return res
47+
48+
def inverse(matrix):
49+
det = determinant(matrix)
50+
if det == 0: return None
51+
52+
matrixMinor = [[] for _ in range(len(matrix))]
53+
for i in range(len(matrix)):
54+
for j in range(len(matrix)):
55+
matrixMinor[i].append(determinant(minor(matrix , i , j)))
56+
57+
cofactors = [[x * (-1) ** (row + col) for col, x in enumerate(matrixMinor[row])] for row in range(len(matrix))]
58+
adjugate = transpose(cofactors)
59+
return scalarMultiply(adjugate , 1/det)
2760

2861
def main():
2962
matrix_a = [[12, 10], [3, 9]]
3063
matrix_b = [[3, 4], [7, 4]]
64+
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
65+
matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
66+
3167
print(add(matrix_a, matrix_b))
3268
print(multiply(matrix_a, matrix_b))
33-
69+
print(identity(5))
70+
print(minor(matrix_c , 1 , 2))
71+
print(determinant(matrix_b))
72+
print(inverse(matrix_d))
3473

3574
if __name__ == '__main__':
3675
main()

0 commit comments

Comments
 (0)