Recursive manipulation of vector elements

后端 未结 3 2021
长发绾君心
长发绾君心 2021-01-13 16:45

I have a vector a and want to multiply each element recursively with b, without using a loop.

a <- rep(0, 10)
a[1] <- 1
b <         


        
3条回答
  •  清歌不尽
    2021-01-13 17:16

    For general recursive series of the form:

    y[i] = x[i] + f[1]*y[i-1] + ... + f[p]*y[i-p]
    

    you can use the filter function. In your case, you have x[i] = 0, f[1] = 2 and f[i] = 0 for i > 1. This translates into:

    filter(rep(0,10), 2, method="recursive", init=1/2)
    # Time Series:
    # Start = 1 
    # End = 10 
    # Frequency = 1 
    #  [1]   1   2   4   8  16  32  64 128 256 512
    

    After you learn how to use it, which is not always obvious the first time, filter is very powerful and efficient. But maybe it is overkill for your geometric case here.

提交回复
热议问题