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 matrix with 'N' rows"""
n=len(g)
T = np.zeros((N,N+n-1))
for x in range(N):
T[x][x:x+n]=g
return T
The usage is simple as:
banded([1,2,3], 3)
and it returns
[1, 2, 3, 0, 0]
[0, 1, 2, 3, 0]
[0, 0, 1, 2, 3]
It will used mostly to solve a finite difference model with a given stencil for example (-1, 1)
Is there a better way to generate that stencil? I could not find any good NumPy Function for that.
By better I mean, faster, using less memory, removing the loop from python and sending to Numpy stack. Any (or all) of those are improvements.