问题描述
我正在尝试将矩阵的对角线(次级对角线,次对角线)上的元素求和.
I'm trying to sum the elements along the antidiagonal (secondary diagonal, minor diagonal) of a matrix.
所以,如果我有一个矩阵m:
So, if I have a matrix m:
m <- matrix(c(2, 3, 1, 4, 2, 5, 1, 3, 7), 3)
m
[,1] [,2] [,3]
[1,] 2 4 1
[2,] 3 2 3
[3,] 1 5 7
我正在寻找总和m[3, 1] + m[2, 2] + m[1, 3]
,即1 + 2 + 1
我不知道如何设置迭代.据我了解,对此没有任何功能(例如diag()
表示另一个对角线).
I can't figure out how to set up an iteration. As far as I know there is no function for this (like diag()
for the other diagonal).
推荐答案
使用
m <- matrix(c(2, 3, 1, 4, 2, 5, 1, 3, 7), 3)
1)反转显示的行(或反转列-未显示),取对角线和总和:
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),或像这样使用row
和col
:
sum(m[c(row(m) + col(m) - nrow(m) == 1)])
## [1] 4
由于row(m) + col(m) - nrow(m)
沿所有反对角线都是恒定的,因此可以推广到其他反对角线.对于这种概括,将c(...)
中的部分写为row(m) + col(m) - nrow(m) - 1 == 0
可能更方便,因为然后用-1替换0使用超对角线,用+1替换使用对角线. -2和2分别使用第二个超对角线和次对角线,依此类推.
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)或使用以下索引顺序:
3) or use this sequence of indexes:
n <- nrow(m)
sum(m[seq(n, by = n-1, length = n)])
## [1] 4
4)或使用outer
这样:
n <- nrow(m)
sum(m[!c(outer(1:n, n:1, "-"))])
## [1] 4
由于outer(1:n, n:1, "-")
沿反对角线是恒定的,因此此对其他反对角线也很好地概括.我们可以将其中的部分写为outer(1:n, n:1) == 0
,如果将0替换为-1,我们将得到超级反对角线,而+1则得到子反对角线. -2和2给出super super和sub sub对角线.例如,sum(m[c(outer(1:n, n:1, "-") == 1)])
是子反对角线的总和.
This one generalizes nicely to other anti-diagonals too as outer(1:n, n:1, "-")
is constant along anti-diagonals. We can write the part within [...] as 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.
这篇关于矩阵的对角线总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!