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
if (a==b)??? otherwise I can't see how this would work ...c(1,8,13,12,9,5,1), i.e. sums of the off-diagonal elements?