Search code examples
rfor-loopif-statementmatrixmatrix-multiplication

setting a limit/threshold for each value in a given row(s) of a matrix during a forloop


I have a for loop for projecting matrices in r and would like to set a "cap" or upper limit/threshold on the values of a given row(s) so they never exceed this values. Below is a sample code and I have commented out my attempt in the forloop. The goal being that any iterative results/results in the third row will not exceed 10000 at any point and if they do, they become 10000. Thanks in advance for the help.

set.seed(123)
A <- lapply(1:50, 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 = 50  # 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   

i1 <- 2:ncol(allYears)

for(t in seq_along(i1)) {
  #ifelse (allYears[3,i1[t]-1] > 10000,10000,allYears[3,i1[t]-1])
  allYears[,i1[t]] <-  A[[t]] %*% allYears[,i1[t]-1]
}

Solution

  • I hope I understand your question clearly. So you are trying to limit the values of the third row to a certain threshold. I think your code is almost there.

    After you decide whether to put the limit in one particular entry through ifelse, you would like to save the (updated) value to your output matrix allYears. Hence, you can get the desired matrix you want.

    set.seed(123)
    A <- lapply(1:50, 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 = 50  # 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   
    
    i1 <- 2:ncol(allYears)
    
    for(t in seq_along(i1)) {
      allYears[,i1[t]] <-  A[[t]] %*% allYears[,i1[t]-1]
    
      ### Check and update the entry for the output matrix ###
      allYears[3,i1[t]] <- ifelse (allYears[3,i1[t]] > 10000, 10000, allYears[3,i1[t]])
    }
    

    Created on 2022-01-25 by the reprex package (v2.0.1)