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.
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.
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.
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.]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With