如何根据规则从较小的矩阵创建较大的矩阵

时间:2020-05-19 15:24:31

标签: python numpy matrix

我有一个矩阵,说3 x 3

x= np.arange(0,9,1).reshape((3,3))

我想根据以下简单规则构建一个更大的矩阵(9x9):

新矩阵的前三行是相同的,并且是从x和零的第一行到结尾。

后三行是相同的,它们是从x的第二行乘以三个0,然后是x,然后是0s到行的末尾,依此类推。像这样的东西。

0 1 2 0 0 0 0 0 0
0 1 2 0 0 0 0 0 0
0 1 2 0 0 0 0 0 0
0 0 0 3 4 5 0 0 0
0 0 0 3 4 5 0 0 0
0 0 0 3 4 5 0 0 0
0 0 0 0 0 0 6 7 8  
0 0 0 0 0 0 6 7 8
0 0 0 0 0 0 6 7 8

有没有办法用Python方式做到这一点?我试图通过使用numpy.kron / numpy.repeat来查看是否,但是我认为不是这样。

我特别想首先得到一个9 * 3矩阵,

x=np.repeat(x,3)

,然后尝试通过使用np.kron用零将其完成,但这没有用。

2 个答案:

答案 0 :(得分:2)

您可以使用scipy.linalg中的block_diag

"""
>>> print(answer)
[[0 1 2 0 0 0 0 0 0]
 [0 1 2 0 0 0 0 0 0]
 [0 1 2 0 0 0 0 0 0]
 [0 0 0 3 4 5 0 0 0]
 [0 0 0 3 4 5 0 0 0]
 [0 0 0 3 4 5 0 0 0]
 [0 0 0 0 0 0 6 7 8]
 [0 0 0 0 0 0 6 7 8]
 [0 0 0 0 0 0 6 7 8]]
"""
from scipy.linalg import block_diag
import numpy as np

x = np.arange(9).reshape(3, 3)
answer = block_diag(*np.array_split(x.repeat(3, axis=0), 3))

答案 1 :(得分:1)

不知道它是什么pythonic,但是我的想法是使用列表理解来遍历每一行,并根据更改的参数np.pad对其进行填充:

import numpy as np

x = np.arange(0,9,1).reshape((3,3))

a = x.shape[1]  # length of original rows | you can hardcode to 3
b = x.shape[0]*a - a  # number of cells you will pad each row with | you can hardcode it to 6
repeat = 3 # how many times each row should be repeated

x_padded = [np.pad(row, (i*a, b-i*a)) for i, row in enumerate(x)]
x_out = np.repeat(x_padded, repeat, axis=0)
print(x_out)

输出:

[[0 1 2 0 0 0 0 0 0]
 [0 1 2 0 0 0 0 0 0]
 [0 1 2 0 0 0 0 0 0]
 [0 0 0 3 4 5 0 0 0]
 [0 0 0 3 4 5 0 0 0]
 [0 0 0 3 4 5 0 0 0]
 [0 0 0 0 0 0 6 7 8]
 [0 0 0 0 0 0 6 7 8]
 [0 0 0 0 0 0 6 7 8]]