以块形式组合Numpy数组 [英] Combining Numpy Arrays in Blockwise Form
问题描述
我有三个Numpy矩阵
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]
,
其中,0
代表具有相关尺寸的零矩阵.
where 0
stands for a matrix of zeros with the relevant dimensions.
推荐答案
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) )
然后您可以通过将2x2的块数组传递到numpy.bmat
来创建块矩阵:
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.]])
另一种方法(更复杂的IMO)是使用 numpy.hstack
和 numpy.vstack
.
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.]])
这篇关于以块形式组合Numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!