Generating banded matrices using numpy

前端 未结 3 2078
梦毁少年i
梦毁少年i 2021-01-06 14:17

I\'m using the following piece of code to create a banded matrix from a generator g:

def banded(g, N):
    \"\"\"Creates a `g` generated banded          


        
3条回答
  •  梦毁少年i
    2021-01-06 14:58

    You can also use scipy's toeplitz function, which is very similar to its matlab counterpart. It is also smart around the shape, do do not worry about the it.

    import scipy.linalg as scl
    
    # define first column and first line
    column1 = [1,0,0]
    line1 = [1,2,3,0,0]
    
    scl.toeplitz(column1, line1)
    

    If you want variable sizes, use your size parameter (N) to add zeros to the columns and lines dynamically. The following is my implementation for finite differences with a minimum size of 3.

    col = [1,0,0] + [0] * (size -3)
    lin = [1,2,1] + [0] * (size -3)
    m = scl.toeplitz(col, lin)
    

    Output:

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

提交回复
热议问题