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
As of NumPy 1.13, there's np.block. This builds matrices out of nested lists of blocks, but it's also more general, handling higher-dimensional arrays and certain not-quite-grid cases. It also produces an ndarray, unlike bmat
.
np.block([[A, B], [B.T, C]])
For previous versions, you can use the NumPy built-in np.bmat that's perfectly suited for such a task, like so -
np.bmat([[A, B], [B.T, C]])
As mentioned in the comments by @unutbu, please note that the output would be a NumPy matrix. If the intended output is an array instead, we need to convert it, like so -
np.asarray(np.bmat([[A, B], [B.T, C]]))
or
np.bmat([[A, B], [B.T, C]]).A
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.