hajto - 4 years ago 68
R Question

# Convert recursive relation to functional program

Hi I am trying to convert the following recursive pseudocode definition into a functional programming construct in R :

``````W = 50
Z = 100

a <- sample(2:5,Z/2,replace=TRUE)
b <- 1/sample(8:32,Z,replace=TRUE)
c <- sample(1:8,W/2,replace=TRUE)/4
d <- 1/sample(40:48,W,replace=TRUE)

Z[n] = Z[n-1] + a*Z[n-1] - b*Z[n-1]-18*W[n-1]
W[n] = W[n-1] + c*W[n-1]- d*W[n-1]
``````

I don't know how I can implement random number in my equations? Can I use a loop?

If I understood your question correctly, something like this should work (also you need to use `a[n], b[n]` etc. in your recurrence relation, since they are vectors):

``````set.seed(1)

W = 50
Z = 100
a <- sample(2:5,Z/2,replace=TRUE)
b <- 1/sample(8:32,Z,replace=TRUE)
c <- sample(1:8,W/2,replace=TRUE)/4
d <- 1/sample(40:48,W,replace=TRUE)

# The recurrence relations
#Z[n] = Z[n-1] + a*Z[n-1] - b*Z[n-1]-18*W[n-1]
#W[n] = W[n-1] + c*W[n-1]- d*W[n-1]

n <- 50
W <- rep(0, n)
Z <- rep(0, n)
# base values
W[1] = 1
Z[1] = 1
# generate Z[2:n]
sapply(2:n, function(i) {Z[i] <<- Z[i-1] + a[i-1]*Z[i-1] - b[i-1]*Z[i-1]-18*W[i-1]; Z[i]})
# [1] -1.405263e+01 -5.572595e+01 -2.755339e+02 -1.633522e+03 -4.719064e+03 -2.784248e+04 -1.651987e+05 -8.177336e+05 -4.054596e+06 -1.193853e+07
#[11] -3.541765e+07 -1.038918e+08 -5.139908e+08 -2.023839e+09 -1.205871e+10 -4.737349e+10 -2.343741e+11 -1.397564e+12 -5.450500e+12 -3.251505e+13
#[21] -1.930581e+14 -5.722794e+14 -2.825630e+15 -8.300287e+15 -3.276429e+16 -1.299650e+17 -3.854135e+17 -1.518983e+18 -9.057638e+18 -3.594750e+19
#[31] -1.417929e+20 -7.032929e+20 -2.771801e+21 -8.142166e+21 -4.853984e+22 -2.389653e+23 -1.424233e+24 -4.143225e+24 -2.042018e+25 -7.982434e+25
#[41] -4.728057e+26 -2.311494e+27 -1.377265e+28 -6.838835e+28 -3.394089e+29 -2.023882e+30 -5.965127e+30 -2.352911e+31 -1.168052e+32
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download