问题描述
我想将矩阵的上部对角线从中间开始相加,在列中递增直到(1,n),n是最后一列,并保存每个对角线的每个和.我的代码只添加了中间的对角线,如何遍历矩阵以获得对角线的总和
I would like to add up the upper part diagonals of a matrix starting from the middle, with increment in column until (1,n), n being the last column and save each sum of every diagonal. My code only add the middle diagonal, how can I loop through the matrix to get the sum of the diagonals
A <- matrix(c(2, 4, 3, 1,
5, 7, 1, 2,
3, 2, 3, 4,
1, 5, 6, 0), # the data elements
nrow = 4, # number of rows
ncol = 4, # number of columns
byrow = TRUE) # fill matrix by rows
sum <- 0
print(A)
for (a in 1){
for (b in 1:ncol){
if (a<-b){
sum = sum + A[a,b]
print (sum)
}
}
}
这是我的结果
> print(A)
[,1] [,2] [,3] [,4]
[1,] 2 4 3 1
[2,] 5 7 1 2
[3,] 3 2 3 4
[4,] 1 5 6 0
for (a in 1){
for (b in 1:ncol){
if (a<-b){
sum = sum + A[a,b]
tail(sum, n=1)
}
}
}
12
推荐答案
您需要diag
提取所有主要对角元素,并需要sum
以获得它们的总和
You need diag
to extract all main diagonal elements and sum
to get the sum of them
sum(diag(A))
我不确定您要的内容是什么,但是如果您还想提取上三角矩阵,则可以使用A[upper.tri(A)]
排除主要的对角线元素,也可以设置diag=TRUE
包括它们A[upper.tri(A, diag = TRUE)]
I am not sure about what you're asking for, but if you also want to extract the upper triangular matrix, you can use A[upper.tri(A)]
which excludes the main diagonal elements, you can also set diag=TRUE
to include them A[upper.tri(A, diag = TRUE)]
@shegzter根据您的评论,可以将col
和row
与逻辑比较==
结合使用以获得所需的数字.
@shegzter based on your comment, you can use col
and row
combined with logical comparison ==
to get the numbers you want.
> A[row(A)==col(A)] # this gives the same out put as `diag(A)`
[1] 2 7 3 0
> A[row(A)+1==col(A)]
[1] 4 1 4
> A[row(A)+2==col(A)]
[1] 3 2
> A[row(A)+3==col(A)]
[1] 1
如果您希望每个元素的总和,请在这些元素上使用sum
:
If you want the sum of each of them, so use sum
over those elements:
> sum(A[row(A)==col(A)])
[1] 12
> sum(A[row(A)+1==col(A)])
[1] 9
> sum(A[row(A)+2==col(A)])
[1] 5
> sum(A[row(A)+3==col(A)])
[1] 1
如果您的目标是获得12 + 9 + 5 + 1的总和,则可以使用upper.tri
和sum
If your objective is getting the following sum 12+9+5+1, then you can do it all at once using upper.tri
and sum
> sum(A[upper.tri(A, diag = TRUE)])
[1] 27
或者没有对角线元素:
> sum(A[upper.tri(A)])
[1] 15
这篇关于使用R将矩阵的对角线相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!