gpt4 book ai didi

python - 将数组从 np.triu_indices 转换为对称矩阵

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:48 24 4
gpt4 key购买 nike

我可以使用以下方法轻松将对称矩阵转换为其三角形分量之一的数组/一维矩阵

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 给出的数组/一维矩阵中获取对称矩阵?

最佳答案

如果您可以使用数组而不是矩阵,您可以简单地进行预分配和分配:

>>> 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]])

关于python - 将数组从 np.triu_indices 转换为对称矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48827236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com