【问题标题】:How to calculate the outer sum (not product) between 2 (1D) vectors如何计算 2(1D)向量之间的外和(不是乘积)
【发布时间】:2021-08-28 05:21:27
【问题描述】:

看来np.einsum 应该可以解决问题,但我无法让它发挥作用。

一个例子:

a = np.arange(3)
b = np.arange(2)

#that computes the outer product
res = np.einsum('i,j->ij',a,b)

#The resulting array I am looking for is:
out = [[0, 1], [1, 2], [2, 3]]
#or its transpose. 

我一直在搜索,所有函数似乎都指向外部产品,而不是外部总和。 for 循环可以完成这项工作,但我希望有一些比这更有效的东西。

有谁知道如何使用np.einsum 或其他东西来实现外部总和?

【问题讨论】:

    标签: python performance numpy numpy-einsum


    【解决方案1】:
    In [610]: a = np.arange(3)
         ...: b = np.arange(2)
         ...: 
    In [611]: np.add.outer(a,b)
    Out[611]: 
    array([[0, 1],
           [1, 2],
           [2, 3]])
    

    通过向a (3,1) 添加维度,我们可以使用加法运算符。详情请查看broadcasting

    In [612]: a[:,None]+b
    Out[612]: 
    array([[0, 1],
           [1, 2],
           [2, 3]])
    

    【讨论】:

      【解决方案2】:

      外和:

      res = np.add.outer(a, b)
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 2022-12-09
      相关资源
      最近更新 更多