如何用NumPy来反转矩阵
矩阵的逆数只是矩阵的倒数,就像我们在正常的算术中对一个数字所做的那样,用来解方程以寻找未知变量的值。矩阵的逆数是指与原矩阵相乘后会得到一个相同的矩阵。 矩阵的逆数只有在矩阵为非星形时才存在,即行列式不应该为0。利用行列式和邻接式,我们可以用下面的公式轻松地找到一个正方形矩阵的逆。
if det(A) != 0
A-1 = adj(A)/det(A)
else
"Inverse doesn't exist"
矩阵方程
其中,
A -1 : 矩阵A的倒数
x: 未知变量列
B: 解决方案矩阵
使用NumPy对矩阵进行反转
Python提供了一个非常简单的方法来计算矩阵的逆值。python NumPy模块中的函数numpy.linalg.inv()可以用来计算矩阵的逆值。
语法:
numpy.linalg.inv(a)
参数:
a:要反转的矩阵
结果:
矩阵a的反转。
示例 1:
# Python program to inverse
# a matrix using numpy
# Import required package
import numpy as np
# Taking a 3 * 3 matrix
A = np.array([[6, 1, 1],
[4, -2, 5],
[2, 8, 7]])
# Calculating the inverse of the matrix
print(np.linalg.inv(A))
输出:
[[ 0.17647059 -0.00326797 -0.02287582]
[ 0.05882353 -0.13071895 0.08496732]
[-0.11764706 0.1503268 0.05228758]]
示例 2:
# Python program to inverse
# a matrix using numpy
# Import required package
import numpy as np
# Taking a 4 * 4 matrix
A = np.array([[6, 1, 1, 3],
[4, -2, 5, 1],
[2, 8, 7, 6],
[3, 1, 9, 7]])
# Calculating the inverse of the matrix
print(np.linalg.inv(A))
输出:
[[ 0.13368984 0.10695187 0.02139037 -0.09090909]
[-0.00229183 0.02673797 0.14820474 -0.12987013]
[-0.12987013 0.18181818 0.06493506 -0.02597403]
[ 0.11000764 -0.28342246 -0.11382735 0.23376623]]
示例 3:
# Python program to inverse
# a matrix using numpy
# 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]]]