由数组生成对称矩阵

在实际应用中,经常会遇上这样的小需求:根据一段给定的数组,生成由这一段数组值构成的对称矩阵。

例如,给定数组[1,2,3,4,5,6,7,8,9,10],要求生成如下的矩阵:
[[0,1,2,3,4],
[1,0,5,6,7],
[2,5,0,8,9],
[3,6,8,0,10],
[4,7,9,10,0]]
其中,对角元全为0,该类型的矩阵完全由给定的数组决定。

笔者给出实现以上功能的一种python参考代码如下:

def semi_to_full(m):
    import numpy as np
    n = len(m)
    n_matrix = int((1+int((1+8*n)**0.5))/2)
    semi_matrix = np.zeros((n_matrix,n_matrix),dtype='int32')

    start_index = 0
    for row in range(n_matrix-1):
        end_index = start_index+(n_matrix-1-row)
        semi_matrix[row,row+1:]=m[start_index:end_index]
        start_index = end_index

    full_matrix = semi_matrix+semi_matrix.T
    
    return full_matrix
代码逻辑如此:先得到数组长度以推定出所欲生成矩阵的规格,接着按照数组值的顺序生成矩阵的上对角元,最后利用对称性完成整个矩阵输出。
该函数参数只有一个,即给定的numpy数组。
Tags: