简体   繁体   中英

Save n matrix in loop R

I´m just new in R and i would like to create n matrix for loop.

I did a loop to create 3 matrix but i don´t know how to save it.

n=numeric(0)

for (i in 1:3){
  n[i]=5^i
  m=numeric(0)
  m=matrix(data=0,nrow=n[i],ncol=n[i])

  for (j in n[i]:1){
    for (k in 1:i){
     m[j,k]=j+k
    }
  }
}

Anyone could help?

thanks

Try this by storing matrix into list.

n=numeric(0)
list_mat <- list()
for (i in 1:3){
  n[i]=5^i
  m=numeric(0)
  m=matrix(data=0,nrow=n[i],ncol=n[i])

  for (j in n[i]:1){
    for (k in 1:i){
      m[j,k]=j+k
    }
  }
  list_mat[[i]] <- m #Holding Matrix
}

Output-

> list_mat[[1]]
   [,1] [,2] [,3] [,4] [,5]
[1,]    2    0    0    0    0
[2,]    3    0    0    0    0
[3,]    4    0    0    0    0
[4,]    5    0    0    0    0
[5,]    6    0    0    0    0

You should store your matrix in a list. Right now, you are just writing over m every time your loop iterates.

   n = numeric(0)
    out = list()
    for (i in 1:3){
      n[i]=5^i
      m=numeric(0)
      m=matrix(data=0,nrow=n[i],ncol=n[i])

      for (j in n[i]:1){
        for (k in 1:i){
          m[j,k]=j+k
        }
      }
      out[[i]] <- m
    }

Even better, construct the list with lapply , not with nested for loops. Like this:

out_apply <- lapply(1:3, function(i) {
  m <- t(t(matrix(rep(1:5^i, i), ncol = i)) + 1:i)
  cbind(m, matrix(data = 0, nrow = 5^i, ncol = 5^i - i))
  })

all.equal(out, out_apply)

[1] TRUE

Consider lapply to build a list of returned items:

matrix_list <- lapply(1:3, function(i) {

  n <- 5^i
  m <- matrix(data=0, nrow=n, ncol=n)

  for (j in n:1){
    for (k in 1:i){
      m[j,k]=j+k
    }
  }

  return(m)
})

Alternatively, build list of matrices with sapply passing multiple vectors which is usually the counterpart to nested for loops. To add to matrix of zeroes, use cbind :

matrix_list2 <- lapply(1:3, function(i) {

  n <- 5^i
  m <- matrix(data=0, nrow=n, ncol=n-i)
  s <- as.matrix(sapply(1:n, `+`, 1:i))

  if (i == 1) m <- cbind(s, m)
  else m <- cbind(t(s), m)

})

Or much more compact, use outer , to run across margins of both for loop vectors:

matrix_list3 <- lapply(1:3, function(i) {      
  n = 5^i
  m <- matrix(data=0, nrow=n, ncol=n-i)      
  m <- cbind(outer(1:n, 1:i, `+`), m)      
})

all.equal(matrix_list, matrix_list2)
# [1] TRUE

all.equal(matrix_list, matrix_list3)
# [1] TRUE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM