块分区对角矩阵

时间:2018-10-26 11:52:42

标签: python numpy

我想像这样生成分区对角矩阵A enter image description here

给出矩阵B

B = -np.diag(np.ones(n - 2), -1) - np.diag(np.ones(n - 2), 1) + 4 * np.diag(np.ones(n - 1))

matrix B

例如, enter image description here

有没有一种方法可以不使用循环?


很抱歉第一次没有正确上传矩阵A和B的图形。

1 个答案:

答案 0 :(得分:3)

您可以将构建块堆叠到查找表中,然后通过索引到其中来构建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
# 0 means 0 0 0 ...,
# 1 means -I
# 2 means B
>>>
# next line builds the lookup table (using np.stack)
# does the lookup ...[A]
# and flattens the resulting 4D array after swapping
# the middle axes; the swap reorders the entries from
# Vert, Horz, vert, horz   to   Vert, vert, Horz, horz
>>> 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属性)。