Skip to content

Commit a7d916e

Browse files
Create matrix_inversion.py
1 parent 0c8cf8e commit a7d916e

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Diff for: linear_algebra/matrix_inversion.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import numpy as np
2+
3+
def invert_matrix(matrix: list[list[float]]) -> list[list[float]]:
4+
"""
5+
Returns the inverse of a square matrix using NumPy.
6+
7+
Parameters:
8+
matrix (list[list[float]]): A square matrix.
9+
10+
Returns:
11+
list[list[float]]: Inverted matrix if invertible, else raises error.
12+
"""
13+
try:
14+
np_matrix = np.array(matrix)
15+
inv_matrix = np.linalg.inv(np_matrix)
16+
return inv_matrix.tolist()
17+
except np.linalg.LinAlgError:
18+
raise ValueError("Matrix is not invertible")
19+
20+
21+
if __name__ == "__main__":
22+
mat = [
23+
[4, 7],
24+
[2, 6]
25+
]
26+
print("Original Matrix:")
27+
print(mat)
28+
print("Inverted Matrix:")
29+
print(invert_matrix(mat))

0 commit comments

Comments
 (0)