Search code examples
rjoinmatrixconcatenationappend

Create and append matrices in a loop using R


I defined a function matrix.create() that generates a m x n Matrix and I'll use a loop to generate matrices for every t = 100 timesteps. The result should be one big matrix of dimension m*t x n.

Is there an easy way to do this? Should I concatenate the matrices within the function?


Solution

  • Here's how (one way) to avoid growing the matrix (inefficient: see e.g. here or chapter 2 here) when every matrix is different:

    res <- list()
    for(t in 1:n){
      res[[i]] <- matrix.create(...)
    }
    mat <- do.call("rbind", res)
    

    Note that growing a list by appending objects (which is basically what we're doing here, although in an R-ish way) does not incur the same penalty as growing vectors, matrices, or data frames.

    It might be slightly more efficient to do this:

    nr <- 10; nc <- 10 ## or whatever
    mat <- matrix(NA_real_, nrow = nr*n, ncol = nc)
    ind <- 1
    for (t in 1:n) {
       mat[ind:(ind+nr),] <- matrix.create(...)
       ind <- ind + nr
    }
    

    Instead of incrementing a current-index variable, you could also do this by computing the appropriate indices at each step (i.e., ((t-1)*nr + 1):(t*nr))