📜  使用 NumPy 计算矩阵的逆

📅  最后修改于: 2022-05-13 01:55:45.949000             🧑  作者: Mango

使用 NumPy 计算矩阵的逆

矩阵的逆只是矩阵的倒数,就像我们在普通算术中对单个数字所做的那样,该数字用于求解方程以找到未知变量的值。矩阵的逆矩阵是与原始矩阵相乘时将作为单位矩阵的矩阵。只有当矩阵是非奇异的,即行列式不应该是 0时,矩阵的逆才存在。使用行列式和伴随,我们可以很容易地使用下面的公式找到方阵的逆,

if det(A) != 0
    A-1 = adj(A)/det(A)
else
    "Inverse doesn't exist"  

矩阵方程

Ax = B\\ =>A^{-1}Ax = A^{-1}B\\ =>x = A^{-1}B

我们可以使用函数numpy.linalg.inv(array) 找出任何方阵的逆。

示例 1:

Python3
# Importing Library
import numpy as np
  
# Finding an inverse of given array
arr = np.array([[1, 2], [5, 6]])
inverse_array = np.linalg.inv(arr)
print("Inverse array is ")
print(inverse_array)
print()
  
# inverse of 3X3 matrix
arr = np.array([[1, 2, 3], 
                [4, 9, 6], 
                [7, 8, 9]])
  
inverse_array = np.linalg.inv(arr)
print("Inverse array is ")
print(inverse_array)
print()
  
# inverse of 4X4 matrix
arr = np.array([[1, 2, 3, 4], 
                [10, 11, 14, 25],
                [20, 8, 7, 55], 
                [40, 41, 42, 43]])
  
inverse_array = np.linalg.inv(arr)
print("Inverse array is ")
print(inverse_array)
print()
  
# inverse of 1X1 matrix
arr = np.array([[1]])
inverse_array = np.linalg.inv(arr)
print("Inverse array is ")
print(inverse_array)


Python3
# Import required package 
import numpy as np 
    
# Inverses of several matrices can 
# be computed at once 
A = np.array([[[1., 2.], [3., 4.]], 
              [[1, 3], [3, 5]]]) 
    
# Calculating the inverse of the matrix 
print(np.linalg.inv(A))


输出:

Inverse array is 
[[-1.5   0.5 ]
 [ 1.25 -0.25]]

Inverse array is 
[[-0.6875     -0.125       0.3125    ]
 [-0.125       0.25       -0.125     ]
 [ 0.64583333 -0.125      -0.02083333]]

Inverse array is 
[[-15.07692308   4.9         -0.8         -0.42307692]
 [ 32.48717949 -10.9          1.8          1.01282051]
 [-20.84615385   7.1         -1.2         -0.65384615]
 [  3.41025641  -1.1          0.2          0.08974359]]

Inverse array is 
[[1.]]

示例 2:

Python3

# Import required package 
import numpy as np 
    
# Inverses of several matrices can 
# be computed at once 
A = np.array([[[1., 2.], [3., 4.]], 
              [[1, 3], [3, 5]]]) 
    
# Calculating the inverse of the matrix 
print(np.linalg.inv(A))

输出:

[[[-2.    1.  ]
  [ 1.5  -0.5 ]]

 [[-1.25  0.75]
  [ 0.75 -0.25]]]