问题描述
我正在尝试对矩阵的对角线(次对角线、次对角线)上的元素求和.
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
:
2) or use row
and col
like this:
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 可能更方便
从那时起,将 0 替换为 -1 使用上对角线,而将 +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, "-")
沿对角线是恒定的.我们可以写成 m[outer(1:n, n:1) == 0]
如果我们用 -1 替换 0 我们得到超反对角线,用 +1 我们得到亚反对角线-对角线.-2 和 2 给出超超和亚亚对角线.例如 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 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.
这篇关于矩阵的对角线之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!