pythonnumpymatrix

How to convert matrix to block matrix using Numpy


Say I have a matrix like

Matrix = [[A11, A12, A13, A14], [A21, A22, A23, A24], [A31, A32, A33, A34], [A41, A42, A43, A44]],

and suppose I want to convert it to a block matrix

[[A,B], [C,D]],

where

A = [[A11, A12], [A21, A22]] B = [[A13, A14], [A23, A24]] C = [[A31, A32], [A41, A42]] D = [[A33, A34], [A43, A44]].

What do I need to type to quickly extract the matrices A, B, C, and D?


Solution

  • Without using loops, you can reshape your array (and reorder the dimensions with moveaxis):

    A, B, C, D = np.moveaxis(Matrix.reshape((2,2,2,2)), 1, 2).reshape(-1, 2, 2)
    

    Or:

    (A, B), (C, D) = np.moveaxis(Matrix.reshape((2,2,2,2)), 1, 2)
    

    For a generic answer on an arbitrary shape:

    x, y = Matrix.shape
    (A, B), (C, D) = np.moveaxis(Matrix.reshape((2, x//2, 2, y//2)), 1, 2)
    

    Output:

    # A
    array([['A11', 'A12'],
           ['A21', 'A22']], dtype='<U3')
    # B
    array([['A13', 'A14'],
           ['A23', 'A24']], dtype='<U3')
    # C
    array([['A31', 'A32'],
           ['A41', 'A42']], dtype='<U3')
    # D
    array([['A33', 'A34'],
           ['A43', 'A44']], dtype='<U3')