Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numpy Matrix tiling and multiplication combination

I’m looking for a function capable of taking a m x n array, which repeats each row n times over a identity-like grid of m size.

For demo:

input = [[a1, b1, c1],
         [a2, b2, c2]]

output = [[a1, b1, c1,  0,  0,  0],
          [a1, b1, c1,  0,  0,  0],
          [a1, b1, c1,  0,  0,  0],
          [ 0,  0,  0, a2, b2, c2],
          [ 0,  0,  0, a2, b2, c2],
          [ 0,  0,  0, a2, b2, c2]]

Last time I asked something similar I was told of the Kronecker product, is there some similar function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Not very elegant perhaps (and I already sense more elegant answers incoming), but it does the job:

import numpy as np
import scipy

a = np.asarray([[11, 21, 31],  [21, 22, 32], [31, 32, 33]])
print(a)
# [[11 21 31]
#  [21 22 32]
#  [31 32 33]]

blocked = scipy.linalg.block_diag(*a)
print(blocked)
# [[11 21 31  0  0  0  0  0  0]
#  [ 0  0  0 21 22 32  0  0  0]
#  [ 0  0  0  0  0  0 31 32 33]]

result = np.repeat(blocked, a.shape[1], axis=0)
print(result)
# [[11 21 31  0  0  0  0  0  0]
#  [11 21 31  0  0  0  0  0  0]
#  [11 21 31  0  0  0  0  0  0]
#  [ 0  0  0 21 22 32  0  0  0]
#  [ 0  0  0 21 22 32  0  0  0]
#  [ 0  0  0 21 22 32  0  0  0]
#  [ 0  0  0  0  0  0 31 32 33]
#  [ 0  0  0  0  0  0 31 32 33]
#  [ 0  0  0  0  0  0 31 32 33]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading