Python 以块形式组合Numpy数组
我有三个Numpy矩阵Python 以块形式组合Numpy数组,python,numpy,matrix,Python,Numpy,Matrix,我有三个Numpy矩阵 a=np.matrix('12;34') b=np.matrix('567;8910') c=np.matrix('1234;456;789') 我想制作以下方块矩阵: M=[ab;0c] 其中0表示具有相关尺寸的零矩阵 创建块矩阵的一种简单方法是(正如@InquisitiveDiot所指出的)。根据要创建的块矩阵判断,需要一个3x2的零矩阵: >>> import numpy as np >>> z = np.zeros( (3, 2
a=np.matrix('12;34')
b=np.matrix('567;8910')
c=np.matrix('1234;456;789')
我想制作以下方块矩阵:
M=[ab;0c]
其中
0
表示具有相关尺寸的零矩阵 创建块矩阵的一种简单方法是(正如@InquisitiveDiot所指出的)。根据要创建的块矩阵判断,需要一个3x2的零矩阵:
>>> import numpy as np
>>> z = np.zeros( (3, 2) )
然后,通过将2x2块数组传递给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更复杂的)方法是使用和
生成和连接分块矩阵的方法:
def blockwise(matrix, block=(3, 3)):
shape = (int(matrix.shape[0] / block[0]), int(matrix.shape[1] / block[1])) + block
strides = (matrix.strides[0] * block[0], matrix.strides[1] * block[1]) + matrix.strides
return as_strided(matrix, shape=shape, strides=strides)
def block_join(blocks):
return np.vstack(map(np.hstack, blocks))
arr = np.arange(36).reshape((6, 6))
blocks = blockwise(arr, (3, 3))
print(blocks)
re_join = block_join(blocks)
print(re_join)
然后输出如下:
>>>>[[[[ 0 1 2]
[ 6 7 8]
[12 13 14]]
[[ 3 4 5]
[ 9 10 11]
[15 16 17]]]
[[[18 19 20]
[24 25 26]
[30 31 32]]
[[21 22 23]
[27 28 29]
[33 34 35]]]]
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]
[24 25 26 27 28 29]
[30 31 32 33 34 35]]
TIL:np.matrix(但不是
np.array
)的字符串语法谢谢,这很有效;下一次将更好地浏览文档。请注意,这将返回一个np.matrix
而不是np.array
>>>>[[[[ 0 1 2]
[ 6 7 8]
[12 13 14]]
[[ 3 4 5]
[ 9 10 11]
[15 16 17]]]
[[[18 19 20]
[24 25 26]
[30 31 32]]
[[21 22 23]
[27 28 29]
[33 34 35]]]]
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]
[24 25 26 27 28 29]
[30 31 32 33 34 35]]