4

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 a block matrix

A    B
B^t  C

where B^t shall denote the transpose of B. Of course, I could do this via a series of concatenations

top_row = np.concatenate([A, B], axis=1)
bottom_row = np.concatenate([B.transpose(), C], axis=1)
result = np.concatenate([top_row, bottom_row], axis=0)

Is there a simpler, more readable way?

1

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

6 Comments

Might be good to note np.bmat returns a matrix, not an array. np.asarray could be used to convert the matrix to an array.
@unutbu Ah yes! Let me add that info.
Thanks! I somehow overlooked np.bmat. I was thinking about using numpy matrices for my problem, anyway.
@lballes Ah so no conversion needed then, awesome!
Might be a useful piece of information for someone else, anyway.
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.