Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sequentially multiply matrices from a list by a vector at time t-1 (recursively) in r

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading