Copy flat list of upper triangle entries to full matrix?

前端 未结 4 1328
礼貌的吻别
礼貌的吻别 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:41

    This version is a slight variation of yours:

    import numpy as np
    
    def utri2mat(utri):
        n = int(-1 + np.sqrt(1 + 8*len(utri))) // 2
        iu1 = np.triu_indices(n)
        ret = np.empty((n, n))
        ret[iu1] = utri
        ret.T[iu1] = utri
        return ret
    

    I replaced

        ret = ret + ret.transpose() - np.diag(ret.diagonal())
    

    with an assignment of utri directly to the transpose of ret:

        ret.T[iu1] = utri
    

    I also removed the argument ntotal and instead computed what n has to be based on the length of utri.

提交回复
热议问题