Adding Diagonals of a matrix using R

狂风中的少年 提交于 2019-12-11 04:12:42

问题


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) 
    }
  }
}

Here is my result

> 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

回答1:


You need diag to extract all main diagonal elements and sum to get the sum of them

sum(diag(A))

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 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

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

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

Or without the diagonal elements:

> sum(A[upper.tri(A)])
[1] 15



回答2:


The following returns the sum for each diagonal:

sapply(split(A, col(A) - row(A)), sum)
# -3 -2 -1  0  1  2  3 
#  1  8 13 12  9  5  1

Hence, to get only the upper, ones you may use

tail(sapply(split(A, col(A) - row(A)), sum), ncol(A))
#  0  1  2  3 
# 12  9  5  1 

The drawback of using tail is that we also compute lower diagonal sums. Hence, to save some time when A is large you may want to use

sapply(split(A[upper.tri(A, diag = TRUE)], (col(A) - row(A))[upper.tri(A, diag = TRUE)]), sum)
#  0  1  2  3 
# 12  9  5  1 


来源:https://stackoverflow.com/questions/49431825/adding-diagonals-of-a-matrix-using-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!