你可以将构建块堆叠成一个查找表,然后通过索引来构建A:
>>> from scipy import sparse
>>>
>>> n = 5
>>> B = sparse.diags([-1, 4, -1], [-1, 0, 1], (n-1, n-1), dtype=int).A
>>> A = sparse.diags([1, 2, 1], [-1, 0, 1], (n-1, n-1), dtype=int).A
>>>
>>> A = np.stack([np.zeros_like(B), -np.identity(n-1, int), B])[A].swapaxes(1, 2).reshape((n-1)*(n-1), -1)
>>> A
array([[ 4, -1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[-1, 4, -1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, -1, 4, -1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, -1, 4, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0],
[-1, 0, 0, 0, 4, -1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0],
[ 0, -1, 0, 0, -1, 4, -1, 0, 0, -1, 0, 0, 0, 0, 0, 0],
[ 0, 0, -1, 0, 0, -1, 4, -1, 0, 0, -1, 0, 0, 0, 0, 0],
[ 0, 0, 0, -1, 0, 0, -1, 4, 0, 0, 0, -1, 0, 0, 0, 0],
[ 0, 0, 0, 0, -1, 0, 0, 0, 4, -1, 0, 0, -1, 0, 0, 0],
[ 0, 0, 0, 0, 0, -1, 0, 0, -1, 4, -1, 0, 0, -1, 0, 0],
[ 0, 0, 0, 0, 0, 0, -1, 0, 0, -1, 4, -1, 0, 0, -1, 0],
[ 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, -1, 4, 0, 0, 0, -1],
[ 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 4, -1, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, -1, 4, -1, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, -1, 4, -1],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, -1, 4]])
请注意,稀疏构造函数仅用于方便起见。稀疏矩阵会立即转换为密集矩阵(使用
.A
属性)。