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

标签 python numpy symmetric

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

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/

相关文章:

python - 线程和 SQLAlchemy session

python - 连接到另一个小部件的事件

python - 如何在OpenCV中找到两个轮廓之间的最近点

tensorflow - 如何强制 tensorflow 张量对称?

搜索部分对称的算法

python - 当我要求用户输入并将其附加到列表时,为什么我的代码没有改变?

python - 将 PCL 链接到 Cython C++ 模块

python - 您将如何提高该功能的性能?

python - 如果列中的第一个值大于最后一个值,Numpy 删除数组中的列

java - 零和等于的对称性