如何从子矩阵形成矩阵? [英] How to form a matrix from submatrices?

查看:116
本文介绍了如何从子矩阵形成矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下4个子矩阵:

Let's say that I have these 4 submatrices:

print(A[0])
print(A[1])
print(A[2])
print(A[3])

[[  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]]

如何管理子矩阵以重现原始矩阵?

How can I manage the submatrix to reproduce the original one?

推荐答案

使用A作为包含这些子矩阵的输入数组,您可以使用某些reshaping并在

With A as the input array containing those sub-matrices, you could use some reshaping and permute dimensions with np.transpose, like so -

A.reshape(2,2,3,3).transpose(0,2,1,3).reshape(-1,6)

说明-

  • 将第一个轴分为两个部分:A.reshape(2,2,3,3).
  • 交换第二轴和第三轴:.transpose(0,2,1,3).
  • 最后,调整形状以包含6列:.reshape(-1,6).
  • Cut the first axis into two parts : A.reshape(2,2,3,3).
  • Swap the second and third axes : .transpose(0,2,1,3).
  • Finally, reshape to have 6 columns : .reshape(-1,6).

因此,解决方案可以像这样概括化-

Thus, the solution could be generalized like so -

m,n,r = A.shape
out = A.reshape(-1,2,n,r).transpose(0,2,1,3).reshape(-1,2*r)

样品运行

让我们重新创建您的A-

In [54]: A = np.arange(36).reshape(-1,3,2,3). transpose(0,2,1,3).reshape(4,3,3)

In [55]: A
Out[55]: 
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]]])

然后,运行我们的代码-

Then, run our code -

In [56]: A.reshape(2,2,3,3).transpose(0,2,1,3).reshape(-1,6)
Out[56]: 
array([[ 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]])

这篇关于如何从子矩阵形成矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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