Block tridiagonal matrix python

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

    Use the function scipy.sparse.diags.

    Example:

    from scipy.sparse import diags
    import numpy as np
    #
    n = 10
    k = np.array([np.ones(n-1),-2*np.ones(n),np.ones(n-1)])
    offset = [-1,0,1]
    A = diags(k,offset).toarray()
    

    This returns:

    array([[-2.,  1.,  0.,  0.,  0.],
           [ 1., -2.,  1.,  0.,  0.],
           [ 0.,  1., -2.,  1.,  0.],
           [ 0.,  0.,  1., -2.,  1.],
           [ 0.,  0.,  0.,  1., -2.]])
    

提交回复
热议问题