对角线上有2D阵列的2D阵列

时间:2020-04-12 06:08:50

标签: python-3.x numpy matrix scipy

我有矩阵

J_plus = 
    [[ 0.0609698  -0.00022921 -0.00022921 ... -0.00022921 -0.00022921
    -0.00022921]
    [-0.00022921  0.0609698  -0.00022921 ... -0.00022921 -0.00022921
    -0.00022921]
    [-0.00022921 -0.00022921  0.0609698  ... -0.00022921 -0.00022921
    -0.00022921]
    ...
    [-0.00022921 -0.00022921 -0.00022921 ...  0.0609698  -0.00022921
    -0.00022921]
    [-0.00022921 -0.00022921 -0.00022921 ... -0.00022921  0.0609698
    -0.00022921]
    [-0.00022921 -0.00022921 -0.00022921 ... -0.00022921 -0.00022921
     0.0609698 ]]

J_minus: 
    [[ 4.46319168e-02 -8.94427191e-05 -8.94427191e-05 ... -8.94427191e-05
     -8.94427191e-05 -8.94427191e-05]
     [-8.94427191e-05  4.46319168e-02 -8.94427191e-05 ... -8.94427191e-05
     -8.94427191e-05 -8.94427191e-05]
     [-8.94427191e-05 -8.94427191e-05  4.46319168e-02 ... -8.94427191e-05
     -8.94427191e-05 -8.94427191e-05]
     ...
     [-8.94427191e-05 -8.94427191e-05 -8.94427191e-05 ...  4.46319168e-02
     -8.94427191e-05 -8.94427191e-05]
     [-8.94427191e-05 -8.94427191e-05 -8.94427191e-05 ... -8.94427191e-05
     4.46319168e-02 -8.94427191e-05]
     [-8.94427191e-05 -8.94427191e-05 -8.94427191e-05 ... -8.94427191e-05
     -8.94427191e-05  4.46319168e-02]]

如何创建矩阵

J = [[J_plus   0];
    [0        J_minus]]

所以最终的矩阵应该是2X2对角矩阵,其中J_plus和J_minus是这样的对角元素

J = [ J_plus    0;
    0         J_minus] 

以numpy表示吗?

1 个答案:

答案 0 :(得分:1)

最简单的方法:scipy.linalg.block_diag

linalg.block_diag(J_plus, J_minus)

对于基于numpy的方法,我们可以使用np.block。虽然绝对不是堆叠多个数组时要走的路:

px, py = J_plus.shape
mx, my = J_minus.shape

np.block([[J_plus,              np.zeros((px, my))], 
          [np.zeros((py, mx)),  J_minus]])

例如:

a = np.arange(16).reshape(4,4)
b = np.arange(24).reshape(4,6)

linalg.block_diag(a, b)

array([[ 0.,  1.,  2.,  3.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 4.,  5.,  6.,  7.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 8.,  9., 10., 11.,  0.,  0.,  0.,  0.,  0.,  0.],
       [12., 13., 14., 15.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  1.,  2.,  3.,  4.,  5.],
       [ 0.,  0.,  0.,  0.,  6.,  7.,  8.,  9., 10., 11.],
       [ 0.,  0.,  0.,  0., 12., 13., 14., 15., 16., 17.],
       [ 0.,  0.,  0.,  0., 18., 19., 20., 21., 22., 23.]])