Best way to create block matrices from separate blocks in numpy?

Consider the code

M=5;N=3;
A11=np.random.rand(M,M);
A12=np.random.rand(M,N);
A21=np.random.rand(N,M);
A22=np.random.rand(N,N);

      

I am new to numpy and am learning it. I want to create a matrix of blocks as follows

RowBlock1=np.concatenate((A11,A12),axis=1)
RowBlock2=np.concatenate((A21,A22),axis=1)
Block=np.concatenate((RowBlock1,RowBlock2),axis=0)

      

Is there an easier way to do this? For example, in matlab, I would do

Block=[[A11,A12];[A21,A22]]

      

and will be done with it. I understand this is only reserved for arrays.

+3


source to share


1 answer


Starting with 1.13 NumPy, numpy.block

:

Block = numpy.block([[A11, A12], [A21, A22]])

      

For previous versions bmat

:

Block = numpy.bmat([[A11, A12], [A21, A22]])

      



numpy.bmat

creates a matrix, not an array. This is usually bad. You can call asarray

the result if you want an array, or use an attribute A

:

Block = numpy.bmat([[A11, A12], [A21, A22]]).A

      

bmat

also does some stack frame operations for you to do this:

Block = numpy.bmat('A11,A12; A21,A22')

      

+8


source







All Articles