Slice NumPy arrays differently along axes (without looping)
I am trying to analyze a temporal signal sampled by a 2D sensor. Effectively, this means integrating the signal values for each sensor pixel (array row/column coordinate) at the times each pixel is active. Since the start time and duration that each pixel is active are different, I effectively need to slice the signal for different values along each row and column.
# Here is the setup for the problem
import numpy as np
def signal(t):
return np.sin(t/2)*np.exp(-t/8)
t = np.arange(13)
array = signal(t)# Example signal on the time axis
starttimes= np.arange(6) # An array of example pixel start times
widths = np.arange(7)+2 # An array of example pixel integration widths
I am currently slicing the array via a for loop:
result_array = np.zeros((6,7)) # A place to store the result
# Here is the loop I am trying to vectorize
for i in range(6): # Different start times and widths for each pixel
for j in range(7):
result_array[i,j] = np.sum(array[starttimes[i]:starttimes[i] + widths[j]]) # Integrate values
print(result_array)
I would like to do this in a more Pythonic/NumPy vectorized way for speed efficiency on large sensors. I thought that np.choose or np.ix_ would work, or maybe some math acting on np.meshgrid, but I can't figure out how to make them select different numbers of values for each column.
Can anyone suggest a NumPy function or other way to do this?
Note: an equivalent loop (that would probably be easier to replicate with NumPy functions) is:
big_new_array = np.zeros((6,7,13)) # Last value at least as long as highest index
for i in range(6):
for j in range(7):
big_new_array[i, j, starttimes[i]:starttimes[i] + widths[j]] = 1
big_new_array *= array[np.newaxis,np.newaxis,:]
result_array = np.sum(big_new_array,axis=-1)
print(result_array)
```
Category Data Science