简体   繁体   中英

R: Storing matrix values to another matrix

I have this code:

mat=matrix(c(0,0,0), nrow=6, ncol=1)
value=matrix();
k=1
repeat{
  mat[]=as.matrix(rep(k), nrow=6, ncol=1)
  print(mat)
  #value[,k]=mat
  if(k==3){
    break
  }
  k=k+1
}

Where I create a matrix mat in each iteration, the values of the matrix mat that are generated are:

    [,1]
[1,]    1
[2,]    1
[3,]    1
[4,]    1
[5,]    1
[6,]    1
     [,1]
[1,]    2
[2,]    2
[3,]    2
[4,]    2
[5,]    2
[6,]    2
     [,1]
[1,]    3
[2,]    3
[3,]    3
[4,]    3
[5,]    3
[6,]    3

And I want to store them on the matrix value which should look like this:

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    2    3
[3,]    1    2    3
[4,]    1    2    3
[5,]    1    2    3
[6,]    1    2    3

This is just a test example, because my actual matrix will be very large, and the number of iterations are unknown, the actual algorithm stops when it fulfills a condition.

You can simply modify your code this way

mat=matrix(c(0,0,0), nrow=6, ncol=1)
k=1
mat.list <- list()  # store each iteration in a list
repeat{
  mat.list[[k]] <- matrix(rep(k), nrow=6, ncol=1)
  print(mat)
  #value[,k]=mat
  if(k==3){
    break
  }
  k=k+1
}
do.call(cbind, mat.list) # combine all list elements into a matrix
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    2    3
[3,]    1    2    3
[4,]    1    2    3
[5,]    1    2    3
[6,]    1    2    3

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