用for循环生成矩阵

时间:2018-10-19 00:50:36

标签: r for-loop matrix

我有一个问题:

在条目上使用for循环生成以下矩阵。

structure(c(3, 2, 2, 2, 2, 1, 3, 0, 0, 0, 1, 0, 3, 0, 0, 1, 0, 
            0, 3, 0, 1, 0, 0, 0, 3), .Dim = c(5L, 5L))
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    3    1    1    1    1
# [2,]    2    3    0    0    0
# [3,]    2    0    3    0    0
# [4,]    2    0    0    3    0
# [5,]    2    0    0    0    3

到目前为止,我的代码是:

z<-matrix(NA,ncol=5,nrow=5)
q<-1:5

 for(n in 1:nrow(z)){
  z[n,] = q
  }
print(z)

我无法形成矩阵。有什么建议么?

1 个答案:

答案 0 :(得分:0)

此解决方案使用嵌套的for循环和if-else语句。

z <- matrix(NA, ncol = 5, nrow = 5)

for (i in 1:nrow(z)){
  for (j in 1:nrow(z)){
    if (i == j){
      z[i, j ] <- 3
    } else if (i == 1){
      z[i, j ] <- 1
    } else if (j == 1){
      z[i, j ] <- 2
    } else {
      z[i, j ] <- 0
    }
  }
}

print(z)
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    3    1    1    1    1
# [2,]    2    3    0    0    0
# [3,]    2    0    3    0    0
# [4,]    2    0    0    3    0
# [5,]    2    0    0    0    3