Trying to vectorize iterative calculation with numpy

前端 未结 3 656
天命终不由人
天命终不由人 2021-01-05 05:15

I am trying to make some piece of code more efficient by using the vectorized form in numpy. Let me show you an example so you know what I mean.

Given the following

3条回答
  •  余生分开走
    2021-01-05 05:27

    A linear recurrence such as this can be computed using scipy.signal.lfilter:

    In [19]: from scipy.signal import lfilter
    
    In [20]: num = np.array([1.0])
    
    In [21]: alpha = 2.0
    
    In [22]: den = np.array([1.0, -alpha])
    
    In [23]: a = np.zeros((4,4))
    
    In [24]: a[0,:] = [1,2,3,4]
    
    In [25]: lfilter(num, den, a, axis=0)
    Out[25]: 
    array([[  1.,   2.,   3.,   4.],
           [  2.,   4.,   6.,   8.],
           [  4.,   8.,  12.,  16.],
           [  8.,  16.,  24.,  32.]])
    

    See the following for more details: python recursive vectorization with timeseries, Recursive definitions in Pandas


    Note that using lfilter really only makes sense if you are solving a nonhomogeneous problem such as x[i+1] = alpha*x[i] + u[i], where u is a given input array. For the simple recurrence a[i+1] = alpha*a[i], you can use the exact solution a[i] = a[0]*alpha**i. The solution for multiple initial values can be vectorized using broadcasting. For example,

    In [271]: alpha = 2.0
    
    In [272]: a0 = np.array([1, 2, 3, 4])
    
    In [273]: n = 5
    
    In [274]: a0 * (alpha**np.arange(n).reshape(-1, 1))
    Out[274]: 
    array([[  1.,   2.,   3.,   4.],
           [  2.,   4.,   6.,   8.],
           [  4.,   8.,  12.,  16.],
           [  8.,  16.,  24.,  32.],
           [ 16.,  32.,  48.,  64.]])
    

提交回复
热议问题