Generating banded matrices using numpy

前端 未结 3 2056
梦毁少年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条回答
  •  囚心锁ツ
    2021-01-06 15:00

    You could use scipy.sparse.diags:

    Input:

    diags([1, 2, 3], [0, 1, 2], shape=(3,5)).toarray()
    

    Output:

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

    The second list, [0, 1, 2], is an offset list. It tells how offset from the diagonal you want a certain element to be.

提交回复
热议问题