注意,与MATLAB不同,python的 *
是元素乘法,而不是矩阵乘法。我们使用该dot
函数来计算向量的内积,将向量乘以矩阵,并乘以矩阵。dot
既可以作为numpy模块中的函数,也可以作为数组对象的实例方法:
#矩阵乘法
import numpy.matlib
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[11,12],[13,14]])
print(np.dot(a,b))
#输出
[[37 40]
[85 92]]
python使用[]输入的时候,默认是输入列向量
import numpy as np
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
v = np.array([9,10])
w = np.array([11, 12])
# Inner product of vectors; both produce 219
print(v.dot(w))
print(np.dot(v, w))
# Matrix / vector product; both produce the rank 1 array [29 67]
print(x.dot(v))
print(np.dot(x, v))
# Matrix / matrix product; both produce the rank 2 array
# [[19 22]
# [43 50]]
print(x.dot(y))
print(np.dot(x, y))