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

我有一个矩阵,比如 3 x 3


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

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


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


后三行是相同的,由 x 的第二行开始,由三个 0 组成,然后是 x,然后是 0,直到行尾,依此类推。像这样的东西。


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

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


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


x=np.repeat(x,3)

然后尝试使用 np.kron 用零完成它,但它没有用。


白衣染霜花
浏览 96回答 2
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_diagimport numpy as npx = np.arange(9).reshape(3, 3)answer = block_diag(*np.array_split(x.repeat(3, axis=0), 3))

红糖糍粑

不确定它是如何 pythonic 但我的想法是使用列表理解来遍历每一行并根据更改的参数对其进行 np.pad :import numpy as npx = np.arange(0,9,1).reshape((3,3))a = x.shape[1]  # length of original rows | you can hardcode to 3b = x.shape[0]*a - a  # number of cells you will pad each row with | you can hardcode it to 6repeat = 3 # how many times each row should be repeatedx_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]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python