We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 0c8cf8e commit a7d916eCopy full SHA for a7d916e
linear_algebra/matrix_inversion.py
@@ -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