Find signal's maximum peak in window I have a 9-dimensional signal (as a csv from this Gist) that looks like this:


A signal peaks every 30 steps. I want to get the maximum values of the peaks in that 30 second window. Here's what I've hacked together so far, where sig is the signal loaded from the csv file and max_res is the desired result:

trial_num = 8
dims = 9
step = 30
max_res = np.zeros(trial_num)

tmp = sig.reshape((trial_num, step, dims))
max_dim = np.argmax(np.sum(tmp, axis=1), axis=1)

sing_dim = np.zeros((trial_num, step))
for t_i in range(trial_num):
    sing_dim[t_i] = tmp[t_i, :, max_dim[t_i]]

max_res = np.max(sing_dim, axis=1)


How can I replace the for-loop with a vectorized operation?
Instead of getting the positions of the maximum value and then retrieving the values thanks to the positions, you can directly ask numpy to retrieve the maximum values:

tmp = sig.reshape((trial_num, step, dims))
max_res = np.max(np.max(tmp, axis=1), axis=1)


I suggest you, however, to use a function to encapsulate this behaviour. It could take the amount of steps per cycle as a parameter and compute the rest from there:

def max_peak_values(data, steps_per_cycle=30):
    length, dims = data.shape
    trials = length // steps_per_cycle
    new_shape = trials, steps_per_cycle, dims

    return np.max(np.max(data.reshape(new_shape), axis=1), axis=1)


and use it like:

max_res = max_peak_values(sig, 30)