How to convert triangle matrix to square in NumPy?

后端 未结 2 2067
逝去的感伤
逝去的感伤 2021-01-04 23:37

I\'m doing some computations on a full matrix that is redundant (i.e. can be a triangle matrix without losing info). I realized I can compute only the lower portion of the

2条回答
  •  春和景丽
    2021-01-05 00:26

    Since the matrix is symetric, you can do:

    m = np.array([1,1,0,1,1,1,0,1,1]).reshape((3,3))
    
    # after some computation you get x
    x = np.tril(m)
    
    m_recomposed = x + x.transpose() - np.diag(np.diag(x))
    
    #array([[1, 1, 0],
    #       [1, 1, 1],
    #       [0, 1, 1]])
    
    #In [152]: np.array_equal(m, m_recomposed)
    #Out[152]: True
    

提交回复
热议问题