Python中的矩阵拆分和乘法

时间:2018-11-22 09:52:44

标签: python algorithm matrix-multiplication

我有2个矩阵:Python中的第一个[P,1]和第二个[N*P,2]

我想将第二个的[P,2]子矩阵的第一个乘以N次(无周期)。

我给你举个例子:

a=[1,2,3]
b=[[1,2],[3,4],[5,6],[7,8],[9,10],[11,12]]

因此,在这种情况下为P=3 N=2。结果应为矩阵[N,2]。在示例中:

res=[[22,28],[58,64]]

我尝试过使用reshape(P,N*2),但我不认为这值得。 有建议吗?

2 个答案:

答案 0 :(得分:0)

根据您的订单,您想要的是

np.sum(a[None,:,None]*b.reshape(2,3,2), axis=1)

您需要在中间空间重新布置数据,因为它们没有像我们期望的那样交错。

答案 1 :(得分:0)

一种以列表理解和最终垂直堆栈计算每个子矩阵的方法

import numpy
a = numpy.array([1, 2, 3])
b = numpy.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
c = numpy.vstack([numpy.dot(a, b[x * a.shape[0]:(x + 1) * a.shape[0], :])
                  for x in range(int(b.shape[0] / a.shape[0]))])
print(c)