将numpy 1D数组转换为邻接矩阵

9o685dep  于 2023-04-06  发布在  其他
关注(0)|答案(2)|浏览(154)

如何转换一个numpy 1D数组:

np.array([1,2,3,4,5,6,7,8,9,10])

到一个邻接矩阵,即在对角线上有零?所需的输出:

[[0 0 0 0 0]
 [1 0 0 0 0]
 [2 5 0 0 0]
 [3 6 8 0 0]
 [4 7 9 10 0]]

输出也可以是一个有上下三角形的矩阵。我已经尝试过numpy.triu和numpy.tril,但不是所有的值都在正确的位置。

50few1ms

50few1ms1#

另一种可能的解决方案:

n = 5

v = np.array([3, 6, 7, 10, 12, 5, 8, 19, 21, 23])

a = np.tril(np.ones((n, n), dtype='int'), -1)
b = np.cumsum(np.roll(a.sum(axis=0), 1))
b[-1] = 0
out = np.cumsum(a + np.diagflat(b), axis=0)
out = np.tril(out, -1)
np.tril(v[out-1], -1)

输出:

array([[ 0,  0,  0,  0,  0],
       [ 3,  0,  0,  0,  0],
       [ 6, 12,  0,  0,  0],
       [ 7,  5, 19,  0,  0],
       [10,  8, 21, 23,  0]])
y1aodyip

y1aodyip2#

有点乱,但能完成任务:

def make_triangular_matrix(values):
  # Compute the appropriate side length for the given input ...
  # good old quadratic equation :-)
  n = (np.sqrt(8*len(values) + 1) - 1) / 2
  if not n.is_integer(): raise Exception("Invalid input length")
  side_length = int(n) + 1

  out = np.zeros((side_length, side_length), dtype=values.dtype)

  # Only interested in the region BELOW the diagonal,
  # which excludes the first row and last column ...
  lower = out[1:,:-1]

  # Assign the values to the appropriate indices (see note about .T)
  lower.T[np.triu_indices_from(lower)] = values

  return out

make_triangular_matrix(np.array([1,2,3,4,5,6,7,8,9,10]))

请注意,在行为主模式中构造上三角区域更自然一些,这就是为什么我们使用上三角索引填充lower.T

相关问题