为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

白衣染霜花 2022-11-29 17:09:06
我有一个矩阵,比如 3 x 3x= np.arange(0,9,1).reshape((3,3))我想根据以下简单规则构建更大的矩阵 (9x9):新矩阵的前三行是相同的,从第一行 x 和零到末尾。后三行是相同的,由 x 的第二行开始,由三个 0 组成,然后是 x,然后是 0,直到行尾,依此类推。像这样的东西。0 1 2 0 0 0 0 0 00 1 2 0 0 0 0 0 00 1 2 0 0 0 0 0 00 0 0 3 4 5 0 0 00 0 0 3 4 5 0 0 00 0 0 3 4 5 0 0 00 0 0 0 0 0 6 7 8  0 0 0 0 0 0 6 7 80 0 0 0 0 0 6 7 8有没有办法以 pythonic 方式做到这一点?我试图通过使用 numpy.kron / numpy.repeat 来查看是否,但我认为这不是方法。特别是我首先想到的是得到一个矩阵 9*3x=np.repeat(x,3)然后尝试使用 np.kron 用零完成它,但它没有用。
查看完整描述

2 回答

?
千万里不及你

TA贡献1784条经验 获得超9个赞

您可以使用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))


查看完整回答
反对 回复 2022-11-29
?
红糖糍粑

TA贡献1815条经验 获得超6个赞

不确定它是如何 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]]


查看完整回答
反对 回复 2022-11-29
  • 2 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信