Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Numpy Arrays in Blockwise Form

I have three Numpy matrices

a = np.matrix('1 2; 3 4')

b = np.matrix('5 6 7; 8 9 10')

c = np.matrix('1 2 3; 4 5 6; 7 8 9')

and I would like to make the following block matrix:

M = [a b ; 0 c],

where 0 stands for a matrix of zeros with the relevant dimensions.

like image 869
Unitarihedron Avatar asked Oct 31 '13 17:10

Unitarihedron


People also ask

How do I combine multiple NumPy arrays into one?

Use numpy. concatenate() to merge the content of two or multiple arrays into a single array. This function takes several arguments along with the NumPy arrays to concatenate and returns a Numpy array ndarray. Note that this method also takes axis as another argument, when not specified it defaults to 0.

How do you make a Boolean NumPy array?

Declaring a Numpy Boolean Array A boolean array can be made using dtype=bool, manually. All values other than '0', 'False', 'None', or empty strings are considered True in a boolean array.


1 Answers

An easy way to create a block matrix is numpy.bmat (as pointed out by @inquisitiveIdiot). Judging by the block matrix you're looking to create, you need a 3x2 matrix of zeros:

>>> import numpy as np
>>> z = np.zeros( (3, 2) )

You can then create a block matrix by passing a 2x2 array of the blocks to numpy.bmat:

>>> M = np.bmat( [[a, b], [z, c]] )
>>> M
matrix([[  1.,   2.,   5.,   6.,   7.],
        [  3.,   4.,   8.,   9.,  10.],
        [  0.,   0.,   1.,   2.,   3.],
        [  0.,   0.,   4.,   5.,   6.],
        [  0.,   0.,   7.,   8.,   9.]])

Another (IMO more complicated) method is to use numpy.hstack and numpy.vstack.

>>> M = np.vstack( (np.hstack((a, b)), np.hstack((z, c))) )
>>> M
matrix([[  1.,   2.,   5.,   6.,   7.],
        [  3.,   4.,   8.,   9.,  10.],
        [  0.,   0.,   1.,   2.,   3.],
        [  0.,   0.,   4.,   5.,   6.],
        [  0.,   0.,   7.,   8.,   9.]])
like image 83
mdml Avatar answered Oct 04 '22 11:10

mdml