Neil G
Neil G

Reputation: 33242

How do numpy block matrices work?

The outcome of this code doesn't make any sense to me:

a = np.zeros((2, 2))
b = np.bmat([[a, a], [a, a]])
print(b.shape, b.dot(np.zeros(4)).shape)

How can a matrix with shape (4, 4) when doing a sum-product over its final axis return a matrix of shape (1, 4)?

Upvotes: 2

Views: 484

Answers (2)

user2357112
user2357112

Reputation: 281476

bmat returns a numpy.matrix instance, as in those things you should never use because they cause all kinds of weird incompatibilities. numpy.matrix always tries to preserve at least two dimensions, so b.dot(np.zeros(4)) is 2D instead of 1D.

Make a numpy.array:

b = np.bmat([[a, a], [a, a]]).A
#                             ^

Or as of NumPy 1.13,

b = np.block([[a, a], [a, a]])

Upvotes: 3

hpaulj
hpaulj

Reputation: 231510

bmat doesn't do anything exotic or fancy; basically it's just a couple of levels on concatenation:

In [308]: np.bmat([[a,a],[a,a]]).A
Out[308]: 
array([[0, 1, 0, 1],
       [2, 3, 2, 3],
       [0, 1, 0, 1],
       [2, 3, 2, 3]])

In [309]: alist = [[a,a],[a,a]]
In [310]: np.concatenate([np.concatenate(sublist, axis=1) for sublist in alist], axis=0)
Out[310]: 
array([[0, 1, 0, 1],
       [2, 3, 2, 3],
       [0, 1, 0, 1],
       [2, 3, 2, 3]])

Upvotes: 1

Related Questions