-2

Hi i'm trying to do the following:-

pvliab <- array(0,c(num_samples,num_time_periods,num_groups))
Ben <- array(0,c(num_samples,num_time_periods,num_groups))

v <- 0.04

pvliab[,1,] <- Ben[,1,]*v
pvliab[,2,] <- Ben[,1,]*v + Ben[,2,]*(v^2)
pvliab[,3,] <- Ben[,1,]*v + Ben[,2,]*(v^2) + Ben[,3,]*(v^3)
pvliab[,4,] <- Ben[,1,]*v + Ben[,2,]*(v^2) + Ben[,3,]*(v^3) + Ben[,4,]*(v^4)

and so on

How do i simplify it using 'for'?

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
user3723264
  • 3
  • 1
  • 3
  • 6
    Who's Ben? Do we know him? – csgillespie Jun 11 '14 at 12:53
  • 4
    Maybe a fan of Ben Bolker :) – Silence Dogood Jun 11 '14 at 12:56
  • Maybe it isn't obvious. @csgillespie is asking for [a reproducible example](http://stackoverflow.com/a/5963610/1412059). E.g., you could edit the output of `dput(Ben)` into your question. – Roland Jun 11 '14 at 12:58
  • Welcome to StackOverflow! Please read the info about [how to ask a question](http://stackoverflow.com/help/how-to-ask) and how to produce a [minimal reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). This will make it much easier for others to help you. – Jaap Jun 11 '14 at 12:58
  • Also, shouldn't it be `Ben[,3,]*(v^3)`? – Roland Jun 11 '14 at 12:59
  • All the same, now that we've had our fun initiating this guy, someone give him the (trivial) `for` loop, eh? `for(j in 1:4) output[j]<-sum(sapply(1:j,input[j]*v^j))` – Carl Witthoft Jun 11 '14 at 13:07
  • yes. what's the best way to simplify the formula @Roland ? and thank you everyone – user3723264 Jun 11 '14 at 13:19

1 Answers1

0

Slow nested loop implementation, but this can be vectorized and sped up consierably if you define a max for j (the index in pvliab[,i,].

for (i in 1:n){
    c = 0
    for (j in 1:i){
        c = c + Ben[,j,]*(v^j)
    }
pvliab[,i,] <- c
}
Vlo
  • 3,168
  • 13
  • 27