0

Hello I want to compute the time difference of two zeros of the first derivative of a signal. For instance, let say the first derivative is:

d =[-0.2, 0.3, 0.2, 0.2, -0.1, 0.5]
t =[   0,  13,  22,  23,   34,  50]

I want to have an array c

c = [(13-0), (34-13), (50-34)], i.e. c = [12, 21, 16]

Let's say that I have the original data recorded for different user in pUser.

z = list()
for i in user:
    sort_ind = np.argsort(pUser.time[i])
    time_vec = pUser.time[i][sort_ind]
    val_vec = pUser.val[i][sort_ind]
    tmp0 = np.diff(val_vec)   
    s = np.sign(tmp0[0])  ## Sign of the first value (+1 or -1)
    index = 0
    zz = list()
    for j in range(1,len(tmp0)):
        if (np.sign(tmp0[j]) + s)==0:
            s = np.sign(tmp0[j])
            dt = (time_vec[j]-time_vec[index])/(2*np.timedelta64(1, 's'))
            zz.append(dt)
            index = j
    z.append(zz)

However because of len(tmp0) ~ 10^4-10^5 that loop takes a while. I am wondering if there is a faster way avoiding that loop.

emax
  • 6,965
  • 19
  • 74
  • 141

1 Answers1

0

How about a pure numpy answer:

import numpy as np

a = np.array([[-0.2, 0.3, 0.2, 0.2, -0.1, 0.5],
              [   0,  13,  22,  23,   34,  50]])

# mask of all the positive values
sign = a[0] > 0

# mask of any location where the sign changed
mask = np.insert(sign[:-1] ^ sign[1:], 0, True)

# mask all the sign changes and diff
c = np.diff(a[1,mask])

output

In [2]: c
Out[2]: array([ 13.,  21.,  16.])
fivetentaylor
  • 1,277
  • 7
  • 11