numpy中具有不同形状的有效乘法矩阵

时间:2018-08-10 12:04:32

标签: python arrays python-3.x numpy

我有两个矩阵A和B:

>>>A
[[1,1,1]
[1,1,1]]
>>>B
[2, 3]

我想有效地将​​它们相乘以获得这样的结果:

>>> A*B
[[2,2,2]
[3,3,3]]

我正在寻找一种比循环迭代更有效的解决方案。有人可以帮忙吗?

5 个答案:

答案 0 :(得分:5)

您可以使用np.multiply在广播中逐元素相乘:

A = np.array([[1,1,1],
              [1,1,1]])

B = np.array([2, 3])

res = np.multiply(A, B[:, None])

print(res)

array([[2, 2, 2],
       [3, 3, 3]])

答案 1 :(得分:2)

最简单的方法就是(A*B.T).T,但习惯于广播可能会更好:

A * B[:, None]

这在功能上与{j {1}}的@jpp答案相同,但是编写起来要短一些

答案 2 :(得分:1)

让:

>>> A = np.array([[1,1,1], #Shape = (2,3)
          [1,1,1]])
>>> A
Out[3]: 
    array([[1, 1, 1],
          [1, 1, 1]])
>>>B = np.array([2, 3])  # shape = (2,)

两者都有不同的形状,所以我们不能做矩阵乘法(逐元素) 因此,我们可以执行A.T,它将A的形状转换为(3,2)

>>> (A.T * B).T
Out[7]: 
       array([[2, 2, 2],
              [3, 3, 3]])

答案 3 :(得分:0)

您的问题违反了数学规则。 矩阵A和B不能相乘,因为A中的列数不等于B中的行数。在这种情况下,这两个矩阵的乘法未定义

答案 4 :(得分:-1)

将5x3矩阵乘以3x2矩阵(真实矩阵乘积)


            /// Basically we're connecting **HalfEdge** pairs to create a connection like follows:
            ///     |
            ///     o
            ///    / \
            /// We also maintain proper Doubly linked list structures for each of Three neighbouring cells
            let vertex = Circle(
                p1: prev.point!,
                p2: newArc.point!,
                p3: next.point!
                )!.center

            prev.rightHalfEdge?.origin = vertex
            next.leftHalfEdge?.destination = vertex

            let lhe = diagram.createHalfEdge(newArc.cell!)
            newArc.leftHalfEdge = lhe
            lhe.origin = vertex
            let lTwin = diagram.createHalfEdge(prev.cell!)
            lTwin.destination = vertex
            makeTwins(lhe, lTwin)

            let rhe = diagram.createHalfEdge(newArc.cell!)
            newArc.rightHalfEdge = rhe
            rhe.destination = vertex
            let rTwin = diagram.createHalfEdge(next.cell!)
            rTwin.origin = vertex
            makeTwins(rhe, rTwin)

            connect(prev: lTwin, next: prev.rightHalfEdge)
            connect(prev: next.leftHalfEdge, next: rTwin)
            connect(prev: rhe, next: lhe)

            prev.rightHalfEdge = lTwin
            next.leftHalfEdge = rTwin