Home > Net >  How to shift array symmetrically in numpy
How to shift array symmetrically in numpy

Time:12-21

I'm very new to Python and asking questions on stack overflow, so I apologize for any formatting errors.

I am working with an autocorrelation array in Python using numpy, and I'd like to shift an array holding its values while using the autocorrelation's property of being an even function. For example, I have an array say,

a = [0,1,2,3,4]

I'd like to be able to shift the array in such a way it shifts but remains symmetric about the number 0 (or the origin of the autocorrelation), and look like this sequence:

    a = [1,0,1,2,3]
    a = [2,1,0,1,2]
    a = [3,2,1,0,1]
    a = [4,3,2,1,0]

Is there an easy way of doing this? I thought about using numpy's roll and flip function, but they don't seem to accomplish exactly what I'm trying to do. Any help/advice would be appreciated, thank you!

Edit:

A more representative example of my question is trying to do the following shift where 1 represents value at the origin of my function:

a = [1, 0.34, 0.59, 0.40, 0.94]
a = [0.34, 1, 0.34, 0.59, 0.40]
a = [0.59, 0.34, 1, 0.34, 0.59]
a = [0.40, 0.59, 0.34, 1, 0.34]
a = [0.94, 0.40, 0.59, 0.34, 1]

Thanks again for any advice/help!

CodePudding user response:

You could add 1 to all elements that appear before zero or are equal to zero, and add -1 to all elements that follow zero. Here is one approach:

values = np.array([1, 0.34, 0.59, 0.40, 0.94])
a = np.array([0,1,2,3,4])
for i in range(a.size):
  print(values[a])
  a  = 2 * (np.arange(a.size) <= a.argmin()) - 1

# [1.   0.34 0.59 0.4  0.94]
# [0.34 1.   0.34 0.59 0.4 ]
# [0.59 0.34 1.   0.34 0.59]
# [0.4  0.59 0.34 1.   0.34]
# [0.94 0.4  0.59 0.34 1.  ]

Alternatively, you could use np.arange with negative range and take absolute values:

for i in range(0, -5, -1):
  print(np.abs(np.arange(i,i 5)))

You could also generate a matrix of all shifted rows in one go:

mat = np.eye(5, dtype=int).cumsum(0).cumsum(0)
mat  = np.rot90(mat, k=2) - np.eye(5, dtype=int) - 1

[[0 1 2 3 4]
 [1 0 1 2 3]
 [2 1 0 1 2]
 [3 2 1 0 1]
 [4 3 2 1 0]]
  • Related