Arranging numpy arrays in a block matrix

前端 未结 2 443
余生分开走
余生分开走 2021-01-21 06:37

I have 3 numpy arrays A, B and C. For simplicity, let\'s assume that they are all of shape [n, n]. I want to arrange them as

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-21 07:09

    Stripped of some bells and whisles, np.bmat does this:

    def foo(alist):
        rowlist=[]
        for row in alist:
            rowlist.append(np.concatenate(row,axis=1))
        return np.concatenate(rowlist, axis=0)
    

    So for example:

    In [1026]: A=np.arange(4).reshape(2,2);B=np.arange(2).reshape(2,1);C=np.array([0]).reshape(1,1)
    
    In [1027]: foo([[A,B],[B.T,C]])
    Out[1027]: 
    array([[0, 1, 0],
           [2, 3, 1],
           [0, 1, 0]])
    

    Making the inputs matrices simplifies the reshape preparation.

提交回复
热议问题