将各种小型2D矩阵交织成一个较大的矩阵 [英] Interlace various small 2D matrices into a bigger one
问题描述
我想将一些小的矩阵交织成一个更大的矩阵.举例来说,假设我有4个4x4矩阵(尽管我正在寻找的解决方案也应适用于非正方形2D矩阵),并且我想将它们的结果结合起来以构建一个8x8矩阵,如下所示:
I have some small matrices that I would like to interlace into a bigger one. Lets say for example that I have 4 matrices of 4x4 (although the solution I am looking for should work with non-square 2D matrices too) and I want to combine their results to build a 8x8 matrix like this:
我得到小矩阵的顺序告诉我它们在大矩阵中的位置.
The order in which I get the small matrices tells me the positions of their elements in the bigger matrix.
我想我可以逐个值地迭代并一次又一次地计算新指数,但是我相信必须有一种更有效的方法来实现它.
I guess I could do it iterating value by value and computing the new indices over and over but I am sure that there has to be a much more efficient way to do it.
推荐答案
方法1
为了提高性能,我建议初始化输出数组,然后通过切片将其分配给它,就像这样-
For performance efficiency, I would suggest initializing the output array and then assigning into it with slicing, like so -
A = [a0,a1,a2,a3] # Input list of arrays
m,n = A[0].shape
out = np.empty((2*m,2*n),dtype=A[0].dtype)
out[::2,::2] = A[0]
out[::2,1::2] = A[1]
out[1::2,::2] = A[2]
out[1::2,1::2] = A[3]
样品运行-
1)输入:
In [67]: a0
Out[67]:
array([[92, 65, 41, 14],
[31, 95, 79, 77],
[98, 89, 26, 68],
[63, 91, 23, 74]])
In [68]: a1
Out[68]:
array([[67, 13, 43, 25],
[18, 15, 38, 34],
[13, 59, 46, 89],
[11, 68, 81, 11]])
In [69]: a2
Out[69]:
array([[12, 53, 81, 91],
[88, 83, 77, 98],
[63, 53, 56, 76],
[58, 64, 57, 68]])
In [70]: a3
Out[70]:
array([[21, 82, 88, 49],
[54, 53, 62, 80],
[89, 96, 72, 62],
[81, 93, 41, 84]])
2)输出:
In [72]: out
Out[72]:
array([[92, 67, 65, 13, 41, 43, 14, 25],
[12, 21, 53, 82, 81, 88, 91, 49],
[31, 18, 95, 15, 79, 38, 77, 34],
[88, 54, 83, 53, 77, 62, 98, 80],
[98, 13, 89, 59, 26, 46, 68, 89],
[63, 89, 53, 96, 56, 72, 76, 62],
[63, 11, 91, 68, 23, 81, 74, 11],
[58, 81, 64, 93, 57, 41, 68, 84]])
方法2
我们还可以使用 np.concatenate
将它们堆叠到一个阵列中,然后转置并最终整形为预期的(2*m,2*n)
形状的阵列,就像这样-
We could also use np.concatenate
to stack those into one array and then transpose and reshape finally into the intended (2*m,2*n)
shaped array, like so -
np.concatenate((A)).reshape(2,2,m,n).transpose(2,0,3,1).reshape(2*m,2*n)
这篇关于将各种小型2D矩阵交织成一个较大的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!