简体   繁体   中英

for loop in matrix using R

I have to put 54 matrices in a list of vector called A. I want the first 25 matrices in this list to be zero matrices except the (i,j)th element of the matrix, which should be equal to one. All my matrices are 5x5. I am using a for loop, but I dont understand how to create the first 25 matrices.

Now I am trying to make 16 matrices of 0 with (i:(i-1),j:(j-1))th element = 1, so that there is a square of 1s of size 2 by 2. For this I have used the following code, but I want to make sure that 'i' is greater that or equal to 2. how can I do this?

    t<-26
for(i in 1:5){
   for(j in 1:5){
     A <- matrix(0, nrow = 5, ncol = 5)
    A[i:(i-1), j:(j-1)] <- 1
    M[[l]] <- A
    t <- t+1
   }
}
A

Just a guess as to what you want. Let me know if this is not what you want, then either I can edit or remove it.

A <- vector("list", 54)
mat <- matrix(0, nrow = 5, ncol = 5)

# assign mat to A and the 1 to the ith element of mat (column wise)
for (i in 1:25) {
  A[[i]] <- mat
  A[[i]][i] <- 1  
}

A[[1]]
# [,1] [,2] [,3] [,4] [,5]
# [1,]    1    0    0    0    0
# [2,]    0    0    0    0    0
# [3,]    0    0    0    0    0
# [4,]    0    0    0    0    0
# [5,]    0    0    0    0    0

A[[2]]
# [,1] [,2] [,3] [,4] [,5]
# [1,]    0    0    0    0    0
# [2,]    1    0    0    0    0
# [3,]    0    0    0    0    0
# [4,]    0    0    0    0    0
# [5,]    0    0    0    0    0

A[[25]]
# [,1] [,2] [,3] [,4] [,5]
# [1,]    0    0    0    0    0
# [2,]    0    0    0    0    0
# [3,]    0    0    0    0    0
# [4,]    0    0    0    0    0
# [5,]    0    0    0    0    1

Insert 1 row wise (not the most elegant way to do it)

# assing 1 the ith element of mat (column wise)
for (i in 1:25) {
  mat_1 <- mat
  mat_1[i] <- 1
  A[[i]] <- t(mat_1)
}

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