Is it possible to vectorize recursive calculation of a NumPy array where each element depends on the previous one?

后端 未结 5 780
猫巷女王i
猫巷女王i 2020-11-27 04:31
T(i) = Tm(i) + (T(i-1)-Tm(i))**(-tau(i))

Tm and tau are NumPy vectors of the same length that have been previously calcul

5条回答
  •  萌比男神i
    2020-11-27 05:23

    You might think this would work:

    import numpy as np
    n = len(Tm)
    t = np.empty(n)
    
    t[0] = 0  # or whatever the initial condition is 
    t[1:] = Tm[1:] + (t[0:n-1] - Tm[1:])**(-tau[1:])
    

    but it doesn't: you can't actually do recursion in numpy this way (since numpy calculates the whole RHS and then assigns it to the LHS).

    So unless you can come up with a non-recursive version of this formula, you're stuck with an explicit loop:

    tt = np.empty(n)
    tt[0] = 0.
    for i in range(1,n):
        tt[i] = Tm[i] + (tt[i-1] - Tm[i])**(-tau[i])
    

提交回复
热议问题