从numpy中的单个块中创建块矩阵的更好方法? [英] Better way to create block matrices out of individual blocks in numpy?
问题描述
考虑代码
M=5;N=3;
A11=np.random.rand(M,M);
A12=np.random.rand(M,N);
A21=np.random.rand(N,M);
A22=np.random.rand(N,N);
我是numpy的新手,正在学习它.我想以以下方式创建一个块矩阵
I am new to numpy and learning it. I want to create a block matrix in the following manner
RowBlock1=np.concatenate((A11,A12),axis=1)
RowBlock2=np.concatenate((A21,A22),axis=1)
Block=np.concatenate((RowBlock1,RowBlock2),axis=0)
有更简单的方法吗?例如:在matlab中,我会做
Is there a more easy way to do it? For eg:, in matlab I would do
Block=[[A11,A12];[A21,A22]]
并完成它.我知道这仅保留给数组.
and will be done with it.I understand that this is reserved only for arrays.
推荐答案
As of NumPy 1.13, there's numpy.block
:
Block = numpy.block([[A11, A12], [A21, A22]])
对于以前的版本,有 bmat
:
For previous versions, there's bmat
:
Block = numpy.bmat([[A11, A12], [A21, A22]])
numpy.bmat
创建一个矩阵,而不是一个数组.这通常是一件坏事.如果需要数组,可以在结果上调用asarray
,或使用
numpy.bmat
creates a matrix, rather than an array. This is usually a bad thing. You can call asarray
on the result if you want an array, or use the A
attribute:
Block = numpy.bmat([[A11, A12], [A21, A22]]).A
bmat
还会弄乱堆栈帧,让您做到这一点:
bmat
also does some messing around with stack frames to let you do this:
Block = numpy.bmat('A11,A12; A21,A22')
这篇关于从numpy中的单个块中创建块矩阵的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!