【发布时间】: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
我想在numpy 中创建一个N x N 数组,使得对角线为零且[x,y] = -[y,x]。
例如:
np.array([[[0,12, 2],
[-12, 0, 3],
[-2, -3, 0]],])
数组中的值可以是任意浮点数。
【问题讨论】:
标签: python numpy numpy-ndarray
一种方法是使用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-assignment 和 masking -
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. ]])
【讨论】:
给你:
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. ]])
【讨论】: