Mengll
Mengll

Reputation: 317

Filling a matrix sequentially using for loop in R

Here's a problem with looping that I can't quite get right.

I want each row of the matrix (w) to be repeatedly filled in matrix (mat) for time "d". matrix (run) is just so I can check that my loops are running correctly by recording the values run through matrix (w).


here's my coding now:

x<-c(0,0,0,0)
y<-c(0,0,0,0)
z<-c(10,50,100,150)
a<-8
b<-4
d<-5

w<-cbind(x,y,z)

run<-matrix(0, ncol=3, nrow=d, byrow=T)
for(h in 1:d){

  mat<-matrix(0, ncol=3, nrow=a, byrow=T)
  for(j in 1:a){
    for(i in 1:b){
      mat[j,]<- w[i,]
    }
  }
  run[h,]<-mat[1,]
}

there's definitely something wrong with the way I'm filling in matrix (mat) because I'm inputting the same value repeatedly instead of sequentially. What should the correct syntax be in this situation?


edit: sorry, to clarify. I want to run my loop 5 times, and for each run, create a matrix (mat) (see below) filled with subsequent rows of matrix (w).

    V1  V2  V3
1   0   0   10
2   0   0   10
3   0   0   10
4   0   0   10
5   0   0   10


    V1  V2  V3
1   0   0   50
2   0   0   50
3   0   0   50
4   0   0   50
5   0   0   50

etc etc...

Upvotes: 1

Views: 2487

Answers (2)

Henrik
Henrik

Reputation: 67778

To create a list of matrices:

lapply(1:nrow(w), function(x) w[rep(x, each = d), ])


# [[1]]
#      x y  z
# [1,] 0 0 10
# [2,] 0 0 10
# [3,] 0 0 10
# [4,] 0 0 10
# [5,] 0 0 10
# 
# ... 
#
# [[4]]
#      x y   z
# [1,] 0 0 150
# [2,] 0 0 150
# [3,] 0 0 150
# [4,] 0 0 150
# [5,] 0 0 150

Upvotes: 3

harkmug
harkmug

Reputation: 2785

Try:

    mat <-  do.call("rbind", lapply(1:nrow(w), function(x) matrix(rep(w[x,],d), nrow=d, byrow=T)))
      [,1] [,2] [,3]
 [1,]    0    0   10
 [2,]    0    0   10
 [3,]    0    0   10
 [4,]    0    0   10
 [5,]    0    0   10
 [6,]    0    0   50
 [7,]    0    0   50
 [8,]    0    0   50
 [9,]    0    0   50
[10,]    0    0   50
[11,]    0    0  100
[12,]    0    0  100
[13,]    0    0  100
[14,]    0    0  100
[15,]    0    0  100
[16,]    0    0  150
[17,]    0    0  150
[18,]    0    0  150
[19,]    0    0  150
[20,]    0    0  150

Upvotes: 2

Related Questions