我可以使用
轻松地将对称矩阵转换为其三角形组件之一的数组/ 1-d矩阵A_symmetric = np.matrix([[1,2][2,3]])
A_array = A_symmetric[np.triu_indices(2)] == np.matrix([1,2,3])
(与tril_indices
相似)
但是如何反转这个操作,即如何从triu_indices
给出的数组/ 1-d矩阵中得到对称矩阵?
答案 0 :(得分:1)
如果你对数组而不是矩阵没问题,你可以简单地预分配并分配:
>>> i, j = np.triu_indices(8)
>>> a = np.arange(i.size)
>>> M = np.empty((8, 8), a.dtype)
>>> M[i, j] = a
>>> M[j, i] = a
>>> M
array([[ 0, 1, 2, 3, 4, 5, 6, 7],
[ 1, 8, 9, 10, 11, 12, 13, 14],
[ 2, 9, 15, 16, 17, 18, 19, 20],
[ 3, 10, 16, 21, 22, 23, 24, 25],
[ 4, 11, 17, 22, 26, 27, 28, 29],
[ 5, 12, 18, 23, 27, 30, 31, 32],
[ 6, 13, 19, 24, 28, 31, 33, 34],
[ 7, 14, 20, 25, 29, 32, 34, 35]])