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
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.]])