numpyblock

numpy 2d array into block matrix


Given a 2x6 array like below

x = np.array([[0,1,2,3,4,5],[6,7,8,9,10,11]])

How do I convert this in to 6x6 matrix with block diagonal filled with above array

Input

input

output I am expecting

output I am expecting

I got the below error while trying to post this. Your post is mostly images. Add additional details to explain the problem and expected results. Please ignore this last bit


Solution

  • Using scipy.linalg.block_diag:

    import numpy as np
    from scipy.linalg import block_diag
    
    x = np.array([[0,  1,  2,  3,  4,  5],
                  [6,  7,  8,  9, 10, 11]])
    x_ = np.split(x, 
                  indices_or_sections = 3,  # modify as needed
                  axis = 1)  
    out = block_diag(*x_)
    
    out
    Out[]: 
    array([[ 0,  1,  0,  0,  0,  0],
           [ 6,  7,  0,  0,  0,  0],
           [ 0,  0,  2,  3,  0,  0],
           [ 0,  0,  8,  9,  0,  0],
           [ 0,  0,  0,  0,  4,  5],
           [ 0,  0,  0,  0, 10, 11]])
    

    Depending on how you want to split up your original array, different permutations of np.split's indices_or_sections parameter will probably handle it the way you want. In this case I used a naive assumption.