Block tridiagonal matrix python

后端 未结 8 1510
甜味超标
甜味超标 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:31

    For building a block-wise tridiagonal matrix from the three individual blocks (and repeat the blocks for N times), one solution can be:

    import numpy as np
    from scipy.linalg import block_diag
    
    def tridiag(c, u, d, N): 
        # c, u, d are center, upper and lower blocks, repeat N times
        cc = block_diag(*([c]*N)) 
        shift = c.shape[1]
        uu = block_diag(*([u]*N)) 
        uu = np.hstack((np.zeros((uu.shape[0], shift)), uu[:,:-shift]))
        dd = block_diag(*([d]*N)) 
        dd = np.hstack((dd[:,shift:],np.zeros((uu.shape[0], shift))))
        return cc+uu+dd
    

    For example:

    c=np.matrix([[1,2],[3,4]])
    u = np.matrix([[5,6],[7,8]])
    d = -1*u
    N=4
    H = tridiag(c,u,d,N)
    print(H)
    

    gives the answer

    [[ 1.  2.  5.  6.  0.  0.  0.  0.]
     [ 3.  4.  7.  8.  0.  0.  0.  0.]
     [-5. -6.  1.  2.  5.  6.  0.  0.]
     [-7. -8.  3.  4.  7.  8.  0.  0.]
     [ 0.  0. -5. -6.  1.  2.  5.  6.]
     [ 0.  0. -7. -8.  3.  4.  7.  8.]
     [ 0.  0.  0.  0. -5. -6.  1.  2.]
     [ 0.  0.  0.  0. -7. -8.  3.  4.]]
    

提交回复
热议问题