2011-05-10 241 views
2

我有一些問題,矩陣乘法:Python矩陣乘法; numpy的陣列

我想多樣信息例如a和b:

a=array([1,3])      # a is random and is array!!! (I have no impact on that) 
            # there is a just for example what I want to do... 

b=[[[1], [2]],      #b is also random but always size(b)= even 
    [[3], [2]], 
    [[4], [6]], 
    [[2], [3]]] 

所以,我想是這樣

[1,3]*[1;2]=7 
[1,3]*[3;2]=9 
[1,3]*[4;6]=22 
[1,3]*[2;3]=11 

到多樣信息所以結果我需要看看:

x1=[7,9] 
x2=[22,8] 

我知道,是非常複雜的,但是我試着2小時實現這一點,但沒有成功:(

+2

這看起來並不像矩陣乘法我 – 2011-05-10 20:15:45

+0

我不是很擅長英語,遺憾的錯誤使用,但我認爲很明顯我想要做什麼....非常感謝 – thaking 2011-05-10 20:22:12

+0

您的示例中有一個錯誤 - 最後一項不應該是[1,3] * [2,3] = 11嗎? – talonmies 2011-05-10 20:26:45

回答

3

如何:

In [16]: a 
Out[16]: array([1, 3]) 

In [17]: b 
Out[17]: 
array([[1, 2], 
     [3, 2], 
     [4, 6], 
     [2, 3]]) 

In [18]: np.array([np.dot(a,row) for row in b]).reshape(-1,2) 
Out[18]: 
array([[ 7, 9], 
     [22, 11]]) 
+5

不必要的複雜解決方案,爲什麼不只是'點(b,a)'?.謝謝 – eat 2011-05-11 09:38:10

-1
result = \ 
[[sum(reduce(lambda x,y:x[0]*y[0]+x[1]*y[1],(a,[b1 for b1 in row]))) \ 
    for row in b][i:i+2] \ 
    for i in range(0, len(b),2)] 
7

b似乎有必要維度。

有了適當的b你可以使用dot(.),如:

In []: a 
Out[]: array([1, 3]) 
In []: b 
Out[]: 
array([[1, 2], 
     [3, 2], 
     [4, 6], 
     [2, 3]]) 
In []: dot(b, a).reshape((2, -1)) 
Out[]: 
array([[ 7, 9], 
     [22, 11]])