2

我想从对角线下方的元素列表中创建一个成熟的矩阵。以下列表包含对角线下方的元素: 在此处输入图像描述

这将是所需的输出:

在此处输入图像描述

到目前为止,我尝试通过实现以下代码在 python 中使用普通的 sintax 进行这项工作:

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)

但是,输出如下:

最终名单:[[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 的副本:将数组转换为三角矩阵,因为我不想创建一个矩阵,其中我的数组值只是下三角矩阵的一部分,而是它们也在上三角矩阵。

4

2 回答 2

2

A solution using numpy.triu_indices and numpy.tril_indices. I have guided each step with comments. The key is to first find the upper right indices, assign the value from the list, then make the matrix symmetric.

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)

Output

[[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. ]]
于 2018-11-19T12:46:21.453 回答
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. ]])

PS:有关我使用此处复制列表的原因的更多详细信息list_similarities[:]

于 2018-11-19T12:58:15.257 回答