简体   繁体   中英

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

I want to shift this matrix circularly [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

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:] . And remaining 0 to len(l)-n-1 elements you put at the end and that is 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!

>>> 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


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

>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM