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

Transforming a list containing the elements below the diagonal of a matrix into a full matrix

我想根据对角线下方的元素列表创建一个完整的矩阵。以下列表包含对角线下方的元素:

这将是所需的输出:

到目前为止,我试图通过实施以下代码在 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 and 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. ]]

使用numpy.triu_indices_from非常简单。

使用这个:

import numpy as np

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

Full_matrix = np.zeros((n,n))
inds = np.triu_indices_from(Full_matrix, k = 0)
# use [:] to copy the list and avoid any problem if the initial list is further needed
Full_matrix[inds] = list_similarities[:]
Full_matrix[(inds[1], inds[0])] = list_similarities[:]

结果

array([[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. ]])

P.S:有关我使用 list_similarities[:] here

复制列表的原因的更多详细信息