Block tridiagonal matrix python

后端 未结 8 1516
甜味超标
甜味超标 2020-11-28 14:52

I would like to create a block tridiagonal matrix starting from three numpy.ndarray. Is there any (direct) way to do that in python?

Thank you in advance!

Ch

8条回答
  •  广开言路
    2020-11-28 15:41

    For better or worse, all the other answers seem to answer about tridiagonal matrices and not block tridiagonal matrices.

    I don't think there is native support for tridiagonal matrices, so I wrote my own code. I had zeros on the main diagonal and my matrix was symmetric.

    Here is my code.

    n1 = 784
    n2 = 256
    n3 = 128
    n4 = 10
    M1 = np.ones((n1,n2))
    M2 = np.ones((n2,n3))
    M3 = np.ones((n3, n4))
    
    def blockTri(Ms):
        #Takes in a list of matrices (not square) and returns a tridiagonal block matrix with zeros on the diagonal
        count = 0
        idx = []
        for M in Ms:
            #print(M.shape)
            count += M.shape[0]
            idx.append(count)
        count += Ms[-1].shape[-1]
        mat = np.zeros((count,count))
        count = 0
        for i, M in enumerate(Ms):
            mat[count:count+M.shape[0],idx[i]:idx[i]+M.shape[1]] = M
            count = count + M.shape[0]
        mat = mat + mat.T    
        return mat
    
    M = blockTri([M1, M2, M3])
    

    Hopefully this can help future people looking for block tridiagonal matrices.

提交回复
热议问题