在块矩阵中排列numpy数组 [英] Arranging numpy arrays in a block matrix

查看:54
本文介绍了在块矩阵中排列numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个numpy数组ABC.为了简单起见,让我们假设它们都是形状为[n, n]的形状.我想将它们排列成一个块矩阵

I have 3 numpy arrays A, B and C. For simplicity, let's assume that they are all of shape [n, n]. I want to arrange them as a block matrix

A    B
B^t  C

其中,B^t表示B的转置.当然,我可以通过一系列串联来做到这一点

where B^t shall denote the transpose of B. Of course, I could do this via a series of concatenations

top_row = np.concatenate([A, B], axis=1)
bottom_row = np.concatenate([B.transpose(), C], axis=1)
result = np.concatenate([top_row, bottom_row], axis=0)

有没有更简单,更易读的方式?

Is there a simpler, more readable way?

推荐答案

从NumPy 1.13开始,存在

As of NumPy 1.13, there's np.block. This builds matrices out of nested lists of blocks, but it's also more general, handling higher-dimensional arrays and certain not-quite-grid cases. It also produces an ndarray, unlike bmat.

np.block([[A, B], [B.T, C]])


对于以前的版本,您可以使用内置的NumPy np.bmat 非常适合这样的任务,就像这样-


For previous versions, you can use the NumPy built-in np.bmat that's perfectly suited for such a task, like so -

np.bmat([[A, B], [B.T, C]])

请在 comments by @unutbu 中提及请注意,输出将是NumPy矩阵.如果预期的输出是数组,则需要将其转换,就像这样-

As mentioned in the comments by @unutbu, please note that the output would be a NumPy matrix. If the intended output is an array instead, we need to convert it, like so -

np.asarray(np.bmat([[A, B], [B.T, C]]))

np.bmat([[A, B], [B.T, C]]).A

这篇关于在块矩阵中排列numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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