Saturday, 24 August 2013

Python - vectorizing a sliding window

Python - vectorizing a sliding window

I'm trying to vectorize a sliding window operation. For the 1-d case a
helpful example could go along the lines of:
x= vstack((np.array([range(10)]),np.array([range(10)])))
x[1,:]=np.where((x[0,:]<5)&(x[0,:]>0),x[1,x[0,:]+1],x[1,:])
The n+1 value for each current value for indices <5. But I get this error:
x[1,:]=np.where((x[0,:]<2)&(x[0,:]>0),x[1,x[0,:]+1],x[1,:])
IndexError: index (10) out of range (0<=index<9) in dimension 1
Curiously I wouldn't get this error for the n-1 value which would mean
indices smaller than 0. It doesn't seem to mind:
x[1,:]=np.where((x[0,:]<5)&(x[0,:]>0),x[1,x[0,:]-1],x[1,:])
print(x)
[[0 1 2 3 4 5 6 7 8 9]
[0 0 1 2 3 5 6 7 8 9]]
Is there anyway around this? is my approach totally wrong? any comments
would be appreciated.

No comments:

Post a Comment