Python矩阵乘法; numpy数组

时间:2011-05-10 20:10:19

标签: python arrays matrix 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个小时来实现这个但没有成功:(

3 个答案:

答案 0 :(得分: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]])

答案 1 :(得分: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]])

答案 2 :(得分:-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)]