我正在寻找一个能够获取
m x n
数组的函数,该数组在 m 大小的类似恒等的网格上重复每一行 n 次。
演示:
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]]
上次问类似的问题,有人告诉我Kronecker的产品,有类似的功能吗?
也许不是很优雅(而且我已经感觉到更优雅的答案即将到来),但它完成了工作:
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]]