以块形式组合Numpy数组 [英] Combining Numpy Arrays in Blockwise Form

查看:84
本文介绍了以块形式组合Numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆