1

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: enter image description here

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.

hipoglucido
  • 545
  • 1
  • 7
  • 20

1 Answers1

3

Approach #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]

Sample run -

1) Input :

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) Output :

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

Approach #2

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)
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • Alternatively I think `vstack`/`hstack`/`dstack` might be able to do the trick as well. – Wolph Mar 19 '17 at 21:47
  • @Wolph Good suggestion! Well, they all use `np.concatenate`. So, performance-wise I don't see the incentive there. – Divakar Mar 19 '17 at 21:50
  • I didn't know that. Carry on :) – Wolph Mar 19 '17 at 21:50
  • @Divakar Interesting! I like your solution in first approach. But, why do we need to put them in list? we could've just used the arrays itself.. – kmario23 Mar 19 '17 at 22:14
  • @kmario23 Well I don't know how the inputs are fed. My convenient assumption was with list of arrays, but essentially it should imply as you suggested one-by-one. – Divakar Mar 19 '17 at 22:16