Copy flat list of upper triangle entries to full matrix?

前端 未结 4 1326
礼貌的吻别
礼貌的吻别 2021-01-21 13:53

I have the upper triangle entries (including diagonal) of a symmetric matrix in a flat list (concatenated rows), and I want to use them to fill in the full matrix, including the

4条回答
  •  无人及你
    2021-01-21 14:27

    Assuming that you have a vector containing the upper triangular values of a symmetric matrix (n x n) then you can re-build the full matrix as follows:

    import numpy as np
    
    # dimension of the full matrix
    n = 80
    
    # artificial upper triangle entries n(n-1) / 2 if matrix is symmetric
    entries = np.array(range((80*79) / 2))
    
    full_matrix = np.zeros((n,n))
    inds = np.triu_indices_from(full_matrix, k = 1)
    full_matrix[inds] = entries
    full_matrix[(inds[1], inds[0])] = entries
    
    print(full_matrix)
    

    Verify:

    np.allclose(full_matrix, full_matrix.T)
    

提交回复
热议问题