How can I transform blocks into a blockdiagonal matrix (NumPy)

后端 未结 3 748
攒了一身酷
攒了一身酷 2020-12-16 15:53

I have three same-size square matrices in NumPy. I would like to combine these to a block-diagonal matrix.

Example:

a1 = np.array([[1,1,1],[1,1,1],[1         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-16 16:17

    scipy.linalg has a block_diag function to do this automatically

    >>> a1 = np.array([[1,1,1],[1,1,1],[1,1,1]])
    >>> a2 = np.array([[2,2,2],[2,2,2],[2,2,2]])
    >>> a3 = np.array([[3,3,3],[3,3,3],[3,3,3]])
    >>> import scipy.linalg
    >>> scipy.linalg.block_diag(a1, a2, a3)
    array([[1, 1, 1, 0, 0, 0, 0, 0, 0],
           [1, 1, 1, 0, 0, 0, 0, 0, 0],
           [1, 1, 1, 0, 0, 0, 0, 0, 0],
           [0, 0, 0, 2, 2, 2, 0, 0, 0],
           [0, 0, 0, 2, 2, 2, 0, 0, 0],
           [0, 0, 0, 2, 2, 2, 0, 0, 0],
           [0, 0, 0, 0, 0, 0, 3, 3, 3],
           [0, 0, 0, 0, 0, 0, 3, 3, 3],
           [0, 0, 0, 0, 0, 0, 3, 3, 3]])
    >>> r = np.array([[1,1,1,0,0,0,0,0,0],[1,1,1,0,0,0,0,0,0],[1,1,1,0,0,0,0,0,0], [0,0,0,2,2,2,0,0,0],[0,0,0,2,2,2,0,0,0],[0,0,0,2,2,2,0,0,0],[0,0,0,0,0,0,3,3,3],[0,0,0,0,0,0,3,3,3],[0,0,0,0,0,0,3,3,3]])
    >>> (scipy.linalg.block_diag(a1, a2, a3)  == r).all()
    True
    

提交回复
热议问题