【问题标题】:numpy array with diagonal equal to zero and [x,y] =-[y,x]对角线为零且 [x,y] =-[y,x] 的 numpy 数组
【发布时间】:2019-10-25 18:30:57
【问题描述】:

我想在numpy 中创建一个N x N 数组,使得对角线为零且[x,y] = -[y,x]

例如:

np.array([[[0,12, 2],
[-12, 0, 3],
[-2, -3, 0]],]) 

数组中的值可以是任意浮点数。

【问题讨论】:

    标签: python numpy numpy-ndarray


    【解决方案1】:

    一种方法是使用scipy.spatial.distance.squareform -

    from scipy.spatial.distance import squareform
    
    def diag_inverted(n):
        l = n*(n-1)//2
        out = squareform(np.random.randn(l))
        out[np.tri(len(out),k=-1,dtype=bool)] *= -1
        return out
    

    另一个 array-assignmentmasking -

    def diag_inverted_v2(n):
        l = n*(n-1)//2
        m = np.tri(n, k=-1, dtype=bool)    
        out = np.zeros((n,n),dtype=float)
        out[m] = np.random.randn(l)
        out[m.T] = -out.T[m.T]
        return out
    

    示例运行 -

    In [148]: diag_inverted(2)
    Out[148]: 
    array([[ 0.        , -0.97873798],
           [ 0.97873798,  0.        ]])
    
    In [149]: diag_inverted(3)
    Out[149]: 
    array([[ 0.        , -2.2408932 , -1.86755799],
           [ 2.2408932 ,  0.        ,  0.97727788],
           [ 1.86755799, -0.97727788,  0.        ]])
    
    In [150]: diag_inverted(4)
    Out[150]: 
    array([[ 0.        , -0.95008842,  0.15135721, -0.4105985 ],
           [ 0.95008842,  0.        ,  0.10321885, -0.14404357],
           [-0.15135721, -0.10321885,  0.        , -1.45427351],
           [ 0.4105985 ,  0.14404357,  1.45427351,  0.        ]])
    

    【讨论】:

    • 我想要 [x,y] = -[y,x]
    • 所以上面的解决方案很棒。我只是想知道这些解决方案与@QuangHoang 发布的解决方案有什么区别?
    • @codingknob 我认为获得所需输出的方法不同。@QuangHoang 的方法有更多的算术运算,所以这可能是一个很大的不同。
    • @codingknob 实际上,这里的解决方案更好,因为它们不会在每个位置减去两个不同的随机数。对于正态分布,后者恰好起作用(尽管它改变了方差),但如果你想要其他东西,比如均匀分布,那么祝你好运。
    【解决方案2】:

    给你:

    size = 3
    
    a = np.random.normal(0,1, (size, size))
    
    ret = (a-a.transpose())/2
    

    输出(随机):

    array([[ 0.        ,  0.11872306,  0.46792054],
           [-0.11872306,  0.        ,  0.12530741],
           [-0.46792054, -0.12530741,  0.        ]])
    

    【讨论】:

    • 你为什么要除以二?
    • 既然你提到了它,我认为没有理由 :-)。谢谢
    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多