目录
1 前言
Python中经常涉及到矩阵运算,其借助于Numpy库进行,因此本文记录一些基于Numpy的矩阵运算
2 点积与矩阵乘法
矩阵的点积(dot product),又称为内积(inner product)
$a = (x_1, y_1), b = (x_2, y_2)$,则$a \cdot b=x_1 x_2 + y_1 y_2$
2.1 np.dot()
如果参与运算的是两个一维数组,则是内积
import numpy as np
a = np.array([1,2,3])
b = np.array([1,2,3])
print(np.dot(a,b))
# output: 14
如果参与的是两个二维以上数组,则结果为矩阵乘法
A = np.array([[1,2,3],
[4,5,6]])
B = np.array([[1,2],
[3,4],
[5,6]])
print(np.dot(A, B))
# output:[[22 28]
# [49 64]]
2.2 np.matmul()和@
对于矩阵乘法,更推荐np.matmul和@
A = np.array([[1,2,3],
[4,5,6]])
B = np.array([[1,2],
[3,4],
[5,6]])
print(np.matmul(A, B))
print(A @ B)
# output: [[22 28]
# [49 64]]
# [[22 28]
# [49 64]]
2.3 np.multiply和*
对于矩阵的标量运算(各个位置的乘积),则考虑用np.multiply和*
A = np.array([[1,2,3],
[4,5,6]])
B = np.array([[1,2,3],
[4,5,6]])
a = np.array([1,2,3])
b = np.array([1,2,3])
print(np.multiply(A, B))
print(np.multiply(a, b))
# output: [[ 1 4 9]
# [16 25 36]]
# [1 4 9]
3 矩阵的逆
在坐标变换的时候,常常涉及到矩阵求逆,使用命令numpy.linalg.inv()
A = [[1,2],[3,4]]
np.linalg.inv(A)
# output: array([[-2. , 1. ],
# [ 1.5, -0.5]])
4 Ref
- https://blog.csdn.net/weixin_43977640/article/details/109908976
- https://blog.csdn.net/FrankieHello/article/details/103510118