python - 将包含矩阵对角线以下元素的列表转换为完整矩阵

标签 python python-3.x matrix matrix-transform

我想从对角线下方的元素列表创建一个完整的矩阵。以下列表包含对角线下方的元素: enter image description here

这将是所需的输出:

enter image description here

到目前为止,我尝试通过实现以下代码来使其与 python 中的正常语法一起工作:

list_similarities = [1,0.1,0.6,0.4,1,0.1,0.2,1,0.7,1]

the_range = range(0,4)

list_of_lists = []
counter_element = 0
counter = -1
for element in the_range:
    counter += 1
    counter_element += len(the_range)-element
    intermediary = (len(the_range)-element)
    first_element = counter_element-intermediary
    line_list = list_similarities[first_element:counter_element]
    # counter = 0, then no need to add an additional element
    # print(line_list)
    if counter == 0:
        "do nothing"
    elif counter >0:
        for item in range(0,element):
            from_list_to_add = list_of_lists[item]
            element_to_add = from_list_to_add[item+1]
            line_list.insert(0,element_to_add)
    print(line_list)
    list_of_lists.append(line_list.copy())
    # print("final lists:", list_of_lists)


# print(counter_element)
print("final lists:", list_of_lists)

但是,输出如下:

final lists: [[1, 0.1, 0.6, 0.4], [0.1, 1, 0.1, 0.2], [0.1, 0.1, 1, 0.7], [0.7, 0.1, 0.1, 1]]

它执行前 2 个列表,代表矩阵中的 2 行,但不会执行后 2 个列表,因为我的代码的工作方式,到目前为止我不知道解决方案。

这是因为我的计数器会使列表超出范围。我查看了很多关于堆栈溢出的帖子,但找不到适合我的情况的东西。如果您能给我指出一个类似的例子,那就完美了。

感谢您的宝贵时间和建议!

更新: 我的问题与 Numpy: convert an array to a triangular matrix 不重复因为我不想创建一个矩阵,其中数组中的值只是下三角矩阵的一部分,而是它们也在上三角矩阵中。

最佳答案

使用 numpy.triu_indices 的解决方案和 numpy.tril_indices 。我用评论来指导每一步。关键是首先找到右上角的索引,从列表中分配值,然后使矩阵对称。

import numpy as np

n = 4
l = [1,0.1,0.6,0.4,1,0.1,0.2,1,0.7,1]

a = np.zeros((n,n)) # Initialize nxn matrix
triu = np.triu_indices(n) # Find upper right indices of a triangular nxn matrix
tril = np.tril_indices(n, -1) # Find lower left indices of a triangular nxn matrix
a[triu] = l # Assign list values to upper right matrix
a[tril] = a.T[tril] # Make the matrix symmetric

print(a)

输出

[[1.  0.1 0.6 0.4]
 [0.1 1.  0.1 0.2]
 [0.6 0.1 1.  0.7]
 [0.4 0.2 0.7 1. ]]

关于python - 将包含矩阵对角线以下元素的列表转换为完整矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53374518/

相关文章:

python - 有可能知道python中子类文件的路径吗?

python - 分发、distutils、setuptools 和 distutils2 之间的区别?

python-3.x - 如何求二叉树中同一层的两个节点之间的水平距离?

javascript - 如何将 html 列表添加到 Django 表单字段

python - 如何将图像加载到 python 3.4 tkinter 窗口中?

c - 求 3X3 矩阵 C 的次矩阵

python - 在 Outlook 中通过电子邮件发送数据

python - 每次有新人连接到我的 Twisted 套接字时,属性都会重置 [python]

Java稀疏矩阵创建

c++ - 矩阵模板加法运算符重载