Somesh Gupta
Somesh Gupta

Reputation: 321

2D array with 2D arrays on the diagonal

I have matrix

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 ]]

and

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]]

how can I create a matrix

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

so the final matrix should be a 2X2 diagonal matrix with J_plus and J_minus as the diagonal elements like this

J = [ J_plus    0;
    0         J_minus] 

in numpy?

Upvotes: 1

Views: 140

Answers (1)

yatu
yatu

Reputation: 88236

The easiest way: scipy.linalg.block_diag:

linalg.block_diag(J_plus, J_minus)

For a numpy based approach, we could use np.block. Though this is definitely not the way to go when it comes to stacking multiple arrays:

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

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

For instance:

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.]])

Upvotes: 1

Related Questions