Question

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

 2  40  2
1 Jan 1970

Solution

 3

I would use numpy indexing with numpy.indices and numpy.full:

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

# get indices
N = x.shape[1]
X, Y = np.indices(x.shape)
shift = np.arange(N)//2*2

# initialize output with -1
# you can pick another value if desired
out = np.full((N, N), -1, dtype=x.dtype)

# assign original values
out[X+shift, Y] = x

Output:

array([[ 0,  1, -1, -1, -1, -1],
       [ 6,  7, -1, -1, -1, -1],
       [-1, -1,  2,  3, -1, -1],
       [-1, -1,  8,  9, -1, -1],
       [-1, -1, -1, -1,  4,  5],
       [-1, -1, -1, -1, 10, 11]])
2024-07-25
mozway

Solution

 1

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.

2024-07-25
Daniel F