【问题标题】:For loop in matrix or similar structure for solving large matrix [duplicate]用于解决大矩阵的矩阵或类似结构中的循环[重复]
【发布时间】:2018-08-13 09:06:49
【问题描述】:
 [Can we have a for loop or other thing for solving the following matrix?
 Matrix A (given 6 x 16)
 a 1 5 6 9 5 8 5 6 7 9 4 6 2 5 4 6
 b 8 6 2 4 7 9 2 3 4 8 6 2 1 6 8 2
 c 9 5 1 7 5 3 7 5 3 9 5 1 2 6 9 3
 d 2 5 6 3 4 1 8 4 2 6 9 5 1 3 7 1
 e 7 4 2 3 6 5 7 4 1 2 3 6 9 8 5 2 
 f 1 5 3 7 8 9 4 6 3 1 5 2 8 9 5 4  

 Output (6 x 4)
 a 1+5+6+9 5+8+5+6 7+9+4+6 2+5+4+6
 b 8+6+2+4 7+9+2+3 4+8+6+2 1+6+8+2
 c 9+5+1+7 5+3+7+5 3+9+5+1 2+6+9+3
 d 2+5+6+3 4+1+8+4 2+6+9+5 1+3+7+1
 e 7+4+2+3 6+5+7+4 1+2+3+6 9+8+5+2
 f 1+5+3+7 8+9+4+6 3+1+5+2 8+9+5+4

 I have a large maxtrix of 4519 x 4519, therefore looking for a for loop.]

 matb <- matrix(data = 0, nrow =6 ,ncol = 6)
    for (a in 1: nrow (data)) {
      for (b in 1:seq (1,5,by=2)) {
          c <- b+1
           matb [a,1:3] <- rbind (sum(data[a,b:c]))


    }  
 }

我尝试使用上述语法,但它不起作用。因此,寻求for循环或函数的帮助来解决这个问题。

【问题讨论】:

    标签: r matrix addition


    【解决方案1】:

    我们可以使用回收来选择交替列,然后添加:

    # example matrix
    m <- matrix(1:12, ncol = 4)
    #      [,1] [,2] [,3] [,4]
    # [1,]    1    4    7   10
    # [2,]    2    5    8   11
    # [3,]    3    6    9   12
    
    m[, c(TRUE, FALSE)] + m[, c(FALSE, TRUE)]
    #       [,1] [,2]
    # [1,]    5   17
    # [2,]    7   19
    # [3,]    9   21
    

    【讨论】:

    • 先生,它适用于给定的数据集,但手头的问题是我必须添加列 1:4,然后是 5:8、9:12 等等。
    • @Litesh 然后您应该发布代表您的实际数据的示例数据。我以重复的形式关闭,请参阅链接的帖子。
    猜你喜欢
    • 2017-11-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 2021-05-24
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多