[英]How to create circularly shift matrix using python
I am writing a code for circular convolution and now I am stuck at position where I need to create circular shift matrix can anyone help me to do this using python or numpy我正在编写循环卷积代码,现在我被困在 position,我需要创建循环移位矩阵任何人都可以使用 python 或 numpy 帮助我做到这一点
I want to shift this matrix circularly [1, -1, 2, 0]
我想循环移动这个矩阵
[1, -1, 2, 0]
I want matrix like,我想要矩阵,
[ 1, -1, 2, 0]
[ 0, 1, -1, 2]
[-2, 0, 1, -1]
[-1, -2, 0, 1]
code:-代码:-
https://drive.google.com/file/d/16XNJ7Q5Iwdlg6Ouz8HU8PgW17xCd1gTp/view?usp=sharing https://drive.google.com/file/d/16XNJ7Q5Iwdlg6Ouz8HU8PgW17xCd1gTp/view?usp=sharing
when you shift by n
you take last n
elements and put then in the front side of the list and that is l[len(l)-n:]
.当您移动
n
时,您将最后n
元素放在列表的前面,即l[len(l)-n:]
。 And remaining 0 to len(l)-n-1
elements you put at the end and that is l[0:len(l)-n]
剩下的 0 到
len(l)-n-1
元素放在最后,即l[0:len(l)-n]
def shift(l,n):
return l[len(l)-n:] + l[0:len(l)-n]
output = []
m = [1, -1, 2, 0]
for i in range(4):
output.append(shift(m, i))
print(output)
# [[1, -1, 2, 0],
# [0, 1, -1, 2],
# [2, 0, 1, -1],
# [-1, 2, 0, 1]]
As suggested in a duplicate, collections.deque.rotate (builtin library) or numpy.roll (more efficient 3rd-party library) is almost-certainly what you're looking for!正如重复建议的那样, collections.deque.rotate (内置库)或numpy.roll (更高效的第 3 方库)几乎肯定是您要找的!
>>> from collections import deque as Deque
>>> d = Deque([1, -1, 2, 0])
>>> d
deque([1, -1, 2, 0])
>>> d.rotate(1)
>>> d
deque([0, 1, -1, 2])
>>> import numpy as np
>>> arr = np.array([1, -1, 2, 0])
>>> np.roll(arr, 1)
array([ 0, 1, -1, 2])
>>> np.roll(arr, 2)
array([ 2, 0, 1, -1])
NOTE that the deque mutates the original collection, while numpy.roll returns a rotated copy请注意,deque 会改变原始集合,而 numpy.roll 会返回旋转后的副本
You can create a single DataFrame by assembling each possible roll for the length of the array, though you may find it's more efficient to calculate the rolls when you need them您可以通过为数组的长度组装每个可能的卷来创建单个 DataFrame,但您可能会发现在需要时计算卷更有效
>>> arr = np.array([1, 2])
>>> pd.DataFrame([np.roll(arr, roll_index) for roll_index in range(len(arr))])
0 1
0 1 2
1 2 1
>>> arr = np.array([1, -1, 2, 0, 9])
>>> pd.DataFrame([np.roll(arr, roll_index) for roll_index in range(len(arr))])
0 1 2 3 4
0 1 -1 2 0 9
1 9 1 -1 2 0
2 0 9 1 -1 2
3 2 0 9 1 -1
4 -1 2 0 9 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.