我想为一个有 n 个点的方程组构建一个分块矩阵。 结果是 (2n+2)x(2n+2) 矩阵。例如,对于 2 个点,矩阵是:
1 0 0 0 0 0
a b c d 0 0
e f g h 0 0
0 0 a b c d
0 0 e f g h
0 0 0 0 0 1
对于 3 个点,矩阵是
1 0 0 0 0 0 0 0
a b c d 0 0 0 0
e f g h 0 0 0 0
0 0 a b c d 0 0
0 0 e f g h 0 0
0 0 0 0 a b c d
0 0 0 0 e f g h
0 0 0 0 0 0 0 1
这里,a、b、c、d、e、f、g、h 是预先知道的浮点值。 但我不知道 n 的值(value)提前。 python中是否有一个库可以做到这一点?我看过 scipy.sparse.diag、scipy.linalg.block_diag 和 numpy.bat,但这些都没有达到我想要的效果。
最佳答案
我们可以使用 np.identity
为我们提供一个“正方形”数组(两个轴上的维度相同),其中包含您指定的 1 和 0:
myarr = np.identity(2*n+2)
然后,我们为 a-h 定义我们的小子集值:
subset = np.array([[a,b,c,d],[e,f,g,h]])
现在替换我们较大数组中的相应值:
for i in range(1, 2*n+2-1, 2):
myarr[i:i+2, i-1:i+3] = subset
编辑:这是我为 a-h 选择的一些随机值的输出:
>>> myarr = np.identity(2*n+2)
>>> subset = np.array([[a,b,c,d],[e,f,g,h]])
>>> for i in range(1, 2*n+2-1, 2):
... myarr[i:i+2, i-1:i+3] = subset
...
>>> myarr
array([[ 1., 0., 0., 0., 0., 0., 0., 0.],
[ 11., 2., 3., 4., 0., 0., 0., 0.],
[ 5., 6., 7., 9., 0., 0., 0., 0.],
[ 0., 0., 11., 2., 3., 4., 0., 0.],
[ 0., 0., 5., 6., 7., 9., 0., 0.],
[ 0., 0., 0., 0., 11., 2., 3., 4.],
[ 0., 0., 0., 0., 5., 6., 7., 9.],
[ 0., 0., 0., 0., 0., 0., 0., 1.]])
关于python - 我如何在 python 中构建这个 block 矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44957372/