Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to efficiently generate an array using 2 arrays and a formula as input with NumPy

I have two arrays, x and t with n elements (t‘s elements are in strict ascending order, so no dividing by 0) and a formula on which the creation of my new array, v is based:

v[i] = (x[i+1] - x[i]) / (t[i+1] - t[i])

How can I write this in NumPy? I tried using numpy.fromfunction but didn’t manage to make it work.

I did manage to do it using a for loop – but I feel like there’s a better way of doing this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

n = 100000
x = np.random.rand(n)
t = np.random.randint(1, 10, n)
t = t.cumsum()

def gen_v(x, t):
    v = np.zeros(n - 1)
    for i in range(0, n - 1):
        v[i] = (x[i+1] - x[i])/(t[i+1]-t[i])
    return v

v = gen_v(x, t)
%timeit gen_v(x, t)

Outputs

156 ms ± 15 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

>Solution :

You can use np.diff():

def gen_v(x,t):
    return np.diff(x)/np.diff(t)

The benchmark give us:

# Your function:
8.45 ms +- 557 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
# My function:
63.4 us +- 1.62 us per loop (mean +- std. dev. of 7 runs, 10000 loops each)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading