【问题标题】:How to construct a matrix of all possible differences of a vector in numpy如何在numpy中构造向量的所有可能差异的矩阵
【发布时间】:2014-09-26 07:07:41
【问题描述】:

我有一个一维数组,可以说:

import numpy as np
inp_vec = np.array([1, 2, 3])

现在,我想构造一个形式的矩阵

[[1 - 1, 1 - 2, 1 - 3],
 [2 - 1, 2 - 2, 2 - 3],
 [3 - 1, 3 - 2, 3 - 3]])

当然可以用 for 循环来完成,但有没有更优雅的方法来做到这一点?

【问题讨论】:

    标签: python numpy array-difference


    【解决方案1】:

    这我也找到了一个不错的方法:

    np.subtract.outer([1,2,3], [1,2,3])
    

    【讨论】:

      【解决方案2】:

      这似乎有效:

      In [1]: %paste
      import numpy as np
      inp_vec = np.array([1, 2, 3])
      
      ## -- End pasted text --
      
      In [2]: inp_vec.reshape(-1, 1) - inp_vec
      Out[2]: 
      array([[ 0, -1, -2],
             [ 1,  0, -1],
             [ 2,  1,  0]])
      

      解释:

      您首先将数组重塑为nx1。当您减去一维数组时,它们都被广播到nxn

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

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

      然后按元素进行减法,这会产生所需的结果。

      【讨论】:

      • 您好,感谢您的回答和解释,但是您能否指出一些参考资料来解释从 nx1 到 nxn 的扩展。这有点神秘。另外我怎么知道减法是按列进行的。谢谢
      • @user3176500 我想说减法是按列或按行进行的并不正确,请参阅编辑。有关规则的简短说明,请查看this tutorial
      • 对不起,错过了“他们都广播到 nxn”。当然,减法是按元素进行的。再次感谢
      • @user3176500 你没有错过,我编辑了答案以回应你的评论:) 很高兴能提供帮助。
      【解决方案3】:
      import numpy as np
      inp_vec = np.array([1, 2, 3])
      
      a, b = np.meshgrid(inp_vec, inp_vec)
      print(b - a)
      

      输出:

      Array([[ 0 -1 -2],
             [ 1  0 -1],
             [ 2  1  0]])
      

      【讨论】:

        【解决方案4】:

        使用 np.nexaxis

        import numpy as np
        inp_vec = np.array([1, 2, 3])
        
        output = inp_vec[:, np.newaxis] - inp_vec
        

        输出

        array([[ 0, -1, -2],
               [ 1,  0, -1],
               [ 2,  1,  0]])
        

        【讨论】:

          【解决方案5】:

          这是一种快速简单的替代方法。

          import numpy as np
          inp_vec = np.array([1, 2, 3])
          
          N = len(inp_vec)
          np.reshape(inp_vec,(N,1)) - np.reshape(inp_vec,(1,N))
          
          

          【讨论】:

            猜你喜欢
            • 2017-11-18
            • 2021-11-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-12-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多