2017-09-14 64 views
0

使用NumPy並嘗試將矩陣相乘有時不起作用。例如爲什麼不能用NumPy乘以一個2,2矩陣?

import numpy as np 

x = np.matrix('1, 2; 3, 8; 2, 9') 
y = np.matrix('5, 4; 8, 2') 

print(np.multiply(x, y)) 

可以返回

Traceback (most recent call last): 
    File "vector-practice.py", line 6, in <module> 
    print(np.multiply(x, y)) 
ValueError: operands could not be broadcast together with shapes (3,2) (2,2) 

我明白,我不能乘這些形狀,但爲什麼不呢?我可以在紙上乘這兩個矩陣,所以爲什麼不在NumPy中?我在這裏錯過了很明顯的東西嗎

回答

4

np.multiply將元素乘以自變量。,這不是一個矩陣乘法。當你有矩陣時,你需要使用*np.dot進行矩陣乘法。

x * y 
#matrix([[21, 8], 
#  [79, 28], 
#  [82, 26]]) 

np.dot(x, y) 
#matrix([[21, 8], 
#  [79, 28], 
#  [82, 26]])