If you are open to numpy
/scipy
(recommended):
Use scipy.linalg.toeplitz
to create banded matrices and numpy.kron
to create patterns of repeated blocks:
import numpy as np
import scipy.linalg
h = 10
K = np.zeros((4,))
K[:2] = (4 / h**2, -1 / h**2)
K = scipy.linalg.toeplitz(K)
L = np.identity(4) / h**2
KK = np.identity(3)
LL = scipy.linalg.toeplitz((0, -1, 0))
A = np.kron(LL, L) + np.kron(KK, K)
# array([[ 0.04, -0.01, 0. , 0. , -0.01, -0. , 0. , 0. , 0. , 0. , 0. , 0. ],
# [-0.01, 0.04, -0.01, 0. , -0. , -0.01, -0. , 0. , 0. , 0. , 0. , 0. ],
# [ 0. , -0.01, 0.04, -0.01, 0. , -0. , -0.01, -0. , 0. , 0. , 0. , 0. ],
# [ 0. , 0. , -0.01, 0.04, 0. , 0. , -0. , -0.01, 0. , 0. , 0. , 0. ],
# [-0.01, -0. , 0. , 0. , 0.04, -0.01, 0. , 0. , -0.01, -0. , 0. , 0. ],
# [-0. , -0.01, -0. , 0. , -0.01, 0.04, -0.01, 0. , -0. , -0.01, -0. , 0. ],
# [ 0. , -0. , -0.01, -0. , 0. , -0.01, 0.04, -0.01, 0. , -0. , -0.01, -0. ],
# [ 0. , 0. , -0. , -0.01, 0. , 0. , -0.01, 0.04, 0. , 0. , -0. , -0.01],
# [ 0. , 0. , 0. , 0. , -0.01, -0. , 0. , 0. , 0.04, -0.01, 0. , 0. ],
# [ 0. , 0. , 0. , 0. , -0. , -0.01, -0. , 0. , -0.01, 0.04, -0.01, 0. ],
# [ 0. , 0. , 0. , 0. , 0. , -0. , -0.01, -0. , 0. , -0.01, 0.04, -0.01],
# [ 0. , 0. , 0. , 0. , 0. , 0. , -0. , -0.01, 0. , 0. , -0.01, 0.04]])
If it has to be pure Python:
Make a matrix of matrices and the use zip
to transpose the middle dimensions and flat list comprehension to make 2D.
K = [[0.04 if i==j else -0.01 if i-j in {-1, 1} else 0.0 for j in range(4)] for i in range(4)]
L = [[-0.01 if i==j else 0.0 for j in range(4)] for i in range(4)]
Z = [[0.0 for j in range(4)] for i in range(4)]
# matrix of matrices
A = [[K if i==j else L if i-j in {-1, 1} else Z for j in range(3)] for i in range(3)]
# make 2d
A = [[a_IJij for a_IJi in a_Ii for a_IJij in a_IJi] for a_I in A for a_Ii in zip(*a_I)]
for a in A:
print(' '.join(f'{i:5.2f}' for i in a))
# 0.04 -0.01 0.00 0.00 -0.01 0.00 0.00 0.00 0.00 0.00 0.00 0.00
# -0.01 0.04 -0.01 0.00 0.00 -0.01 0.00 0.00 0.00 0.00 0.00 0.00
# 0.00 -0.01 0.04 -0.01 0.00 0.00 -0.01 0.00 0.00 0.00 0.00 0.00
# 0.00 0.00 -0.01 0.04 0.00 0.00 0.00 -0.01 0.00 0.00 0.00 0.00
# -0.01 0.00 0.00 0.00 0.04 -0.01 0.00 0.00 -0.01 0.00 0.00 0.00
# 0.00 -0.01 0.00 0.00 -0.01 0.04 -0.01 0.00 0.00 -0.01 0.00 0.00
# 0.00 0.00 -0.01 0.00 0.00 -0.01 0.04 -0.01 0.00 0.00 -0.01 0.00
# 0.00 0.00 0.00 -0.01 0.00 0.00 -0.01 0.04 0.00 0.00 0.00 -0.01
# 0.00 0.00 0.00 0.00 -0.01 0.00 0.00 0.00 0.04 -0.01 0.00 0.00
# 0.00 0.00 0.00 0.00 0.00 -0.01 0.00 0.00 -0.01 0.04 -0.01 0.00
# 0.00 0.00 0.00 0.00 0.00 0.00 -0.01 0.00 0.00 -0.01 0.04 -0.01
# 0.00 0.00 0.00 0.00 0.00 0.00 0.00 -0.01 0.00 0.00 -0.01 0.04