gpt4 book ai didi

numpy - 一维数组的所有循环移位的二维数组

转载 作者:行者123 更新时间:2023-12-04 17:08:15 24 4
gpt4 key购买 nike

假设 a是一些 1d numppy.array有 n 个元素:

a = np.array([a_0, a_1, ..., a_n_minus_1])

我想生成 2d (n X n) numpy.array在第 i 行包含 a 的第 i 个循环移位:
np.array([[a_0, a_1, ..., a_n_minus_1], [a_n_minus_1, a_0, a_1, ...], ...]])

最好没有循环。如何有效地做到这一点?

(函数 np.roll 似乎相关,但显然只需要一个标量 shift 。)

最佳答案

你实际上是在构建一个循环矩阵。只需使用 scipy circulant function .小心,因为你必须传入第一个垂直列,而不是第一行:

from scipy.linalg import circulant
circulant([1,4,3,2]
> array([[1, 2, 3, 4],
[4, 1, 2, 3],
[3, 4, 1, 2],
[2, 3, 4, 1]]

作为引用,循环矩阵非常好 properties .

关于numpy - 一维数组的所有循环移位的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35924194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com