簡體   English   中英

乘以一維數組x二維數組python

[英]Multiply a 1d array x 2d array python

我有一個2d數組和一個1d數組,我需要將1d數組中的每個元素乘以2d數組列中的每個元素。 它基本上是矩陣乘法,但由於1d數組,numpy不允許進行矩陣乘法。 這是因為矩陣本質上是numpy的2d。 我該如何解決這個問題? 這是我想要的一個例子:

FrMtx = np.zeros(shape=(24,24)) #2d array
elem = np.zeros(24, dtype=float) #1d array
Result = np.zeros(shape=(24,24), dtype=float) #2d array to store results

some_loop to increment i:
    some_other_loop to increment j:
        Result[i][j] = (FrMtx[i][j] x elem[j])

許多努力給了我很多錯誤,例如arrays used as indices must be of integer or boolean type

由於NumPy的廣播規則,

Result = FrMtx * elem

將給出期望的結果。

您應該能夠將數組相乘,但是由於矩陣是正方形,所以將數組相乘的方向不是很明顯。 為了更明確地知道要相乘的軸,我發現始終相乘具有相同維數的數組會很有幫助。

例如,要乘以列:

mtx = np.zeros(shape=(5,7))
col = np.zeros(shape=(5,))
result = mtx * col.reshape((5, 1))  

通過將col重塑為(5,1),我們保證mtx的軸0與col的軸0相乘。 要乘以行:

mtx = np.zeros(shape=(5,7))
row = np.zeros(shape=(7,))
result = mtx * row.reshape((1, 7))

這樣可以確保mtx中的軸1與行中的軸0相乘。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM