Sum of antidiagonal of a matrix

前端 未结 4 1896
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 14:29

I\'m trying to sum the elements along the antidiagonal (secondary diagonal, minor diagonal) of a matrix.

So, if I have a matrix m:

m <- matrix(c(2         


        
相关标签:
4条回答
  • 2020-12-05 15:09

    You could index out the elements you want to sum

    sum(m[cbind(3:1, 1:3)])
    
    0 讨论(0)
  • 2020-12-05 15:10

    Using

    m <- matrix(c(2, 3, 1, 4, 2, 5, 1, 3, 7), 3)
    

    1) Reverse the rows as shown (or the columns - not shown), take the diagonal and sum:

    sum(diag(m[nrow(m):1, ]))
    ## [1] 4
    

    2) or use row and col like this:

    sum(m[c(row(m) + col(m) - nrow(m) == 1)])
    ## [1] 4
    

    This generalizes to other anti-diagonals since row(m) + col(m) - nrow(m) is constant along all anti-diagonals. For such a generalization it might be more convenient to write the part within c(...) as row(m) + col(m) - nrow(m) - 1 == 0 since then replacing 0 with -1 uses the superdiagonal and with +1 uses the subdiagonal. -2 and 2 use the second superdiagonal and subdiagonal respectively and so on.

    3) or use this sequence of indexes:

    n <- nrow(m)
    sum(m[seq(n, by = n-1, length = n)])
    ## [1] 4
    

    4) or use outer like this:

    n <- nrow(m)
    sum(m[!c(outer(1:n, n:1, "-"))])
    ## [1] 4
    

    This one generalizes nicely to other anti-diagonals too as outer(1:n, n:1, "-") is constant along anti-diagonals. We can write m[outer(1:n, n:1) == 0] and if we replace 0 with -1 we get the super anti-diagonal and with +1 we get the sub anti-diagonal. -2 and 2 give the super super and sub sub antidiagonals. For example sum(m[c(outer(1:n, n:1, "-") == 1)]) is the sum of the sub anti-diagonal.

    0 讨论(0)
  • 2020-12-05 15:10

    This is sometimes called the "secondary diagonal" or "minor diagonal".

    Another short solution:

    sum(diag(apply(m,2,rev)))
    
    0 讨论(0)
  • 2020-12-05 15:32

    Here is a simple way without using a loop, assuming that your matrix is m:

    sum(diag(matrix(c(m[,3],m[,2],m[,1]), nrow=3)))
    
    0 讨论(0)
提交回复
热议问题