Numpy: calculate based on previous element?

后端 未结 5 2279
北恋
北恋 2021-02-08 15:45

Say that I have array x and y:

x = numpy.array([1,2,3,4,5,6,7,8,9,10])  # actual content is the a result of another calculation step
         


        
5条回答
  •  北海茫月
    2021-02-08 16:28

    If you need a recursive computation, if your y[i] should depend on the computed y[i-1] from the same run, then there seems to be no built-in solution in numpy, and you will need to compute it using a simple for loop:

    y = np.empty(x.size)
    last = 50
    for i in range(x.size):
        y[i] = last = last * 2 + x[i]
    

    See this question: Is a "for" loop necessary if elements of the a numpy vector are dependant upon the previous element?

    Otherwise, you can implement your formula in one line using numpy:

    y = np.concatenate(([50], y[:-1])) * 2 + x
    

    Explanation:

    y[:-1]
    

    Creates a N-1-sized array: y_0, y_1, ... y_N-1.

    np.concatenate(([50], y[:-1]))
    

    Creates a N-sized array with the first element your starting value 50. So this expression basically is your y[i-1].

    Then you can do the math element-wise using numpy array arithmetics.

提交回复
热议问题