I am trying to multiply a list of matrices, in the order they appear within the list starting with matrix 1, by an initial vector and then recursively; so matrix 2 from the list multiplied by that resulting vector. I have tried various iteration of lapply and map but am unable to project forward and perform this recursively. More explicitly: A[[1]] % * % allYears[,1], then A[[2]] % * % allYears[,2],…..,A[[4]] % * % allYears[,4] which produces the final 5th column in allYears. Below is the sample code with the known error in the for loop at A[[i]] indexing as i is not explicitly referenced. Thanks in advance for the help.
A <- lapply(1:4, function(x) # construct list of matrices
matrix(c(0, 0, 10,
rbeta(1,5,4), 0, 0,
0, rbeta(1,10,2), 0), nrow = 3,ncol=3, byrow = TRUE, ))
n <- c(1000,100,10) # initial vector of abundances
nYears = 4 # define the number of years to project over
allYears <- matrix(0,nrow=3,ncol=nYears+1) # build a storage array for all abundances
allYears[,1] <- n # set the year 0 abundance
for(t in 1:(nYears+1)){ # loop through all years
allYears[,t] <- A[[i]] %*% allYears[,t-1]
}
>Solution :
Based on the description, perhaps we need to loop over the sequence – i.e. length of A is 4, whereas the number of columns of ‘allYears’ is 5. Create an index from 2 to ncol of ‘allYears’, then loop over the sequence of that index, extract the corresponding element of ‘A’ based on the sequence whereas we get the allYears previous column
i1 <- 2:(nYears + 1)
for(t in seq_along(i1)) {
allYears[,i1[t]] <- A[[t]] %*% allYears[,i1[t]-1]
}
-output
> allYears
[,1] [,2] [,3] [,4] [,5]
[1,] 1000 100.00000 817.24277 2081.08322 333.6702
[2,] 100 261.46150 55.44237 423.22095 1244.6680
[3,] 10 81.72428 208.10832 33.36702 355.5175