更新时间:2022-06-04 03:11:01
对于 matrix
对象的元素乘法,您可以使用 numpy.multiply
:
For elementwise multiplication of matrix
objects, you can use numpy.multiply
:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.multiply(a,b)
结果
array([[ 5, 12],
[21, 32]])
然而,你真的应该使用 array
而不是 matrix
.matrix
对象与常规 ndarray 有各种可怕的不兼容.使用 ndarrays,您可以只使用 *
进行元素乘法:
However, you should really use array
instead of matrix
. matrix
objects have all sorts of horrible incompatibilities with regular ndarrays. With ndarrays, you can just use *
for elementwise multiplication:
a * b
如果您使用的是 Python 3.5+,您甚至不会失去使用运算符执行矩阵乘法的能力,因为 @
现在做矩阵乘法:
If you're on Python 3.5+, you don't even lose the ability to perform matrix multiplication with an operator, because @
does matrix multiplication now:
a @ b # matrix multiplication