Summing Matrix Elements

I have a matrix from which I want to sum elements without including diagonals. Suppose

 matrixDat <- matrix(1:25, ncol=5)
 colnames(matrixDat) <- c("A", "B", "C", "D", "E")
  rownames(matrixDat) <- c("A", "B", "C", "D", "E")

      

The result I am expecting is the following:

c(2+6, 3+11, 4+16, 5+21, 8+12, 9+17, 10+22, 14+18, 15+23, 20+24)

      

i.e. summing the 1st row and 1st column without 1. Once it is complete, remove the first row and first column, start at the second row and second column, then remove it, do the process with the third row, third column until will not reach the fifth line, fith column.

+3


source to share


1 answer


Try:

     indx <- lower.tri(matrixDat)
     matrixDat[indx]+t(matrixDat)[indx]
     #[1]  8 14 20 26 20 26 32 32 38 44

      



Or you can do a loop

    vec1 <- vector()
    for(i in 1:ncol(m1)){
    vec1 <- c(vec1,matrixDat[,i][-(1:i)]+matrixDat[i,][-(1:i)])
     }

     unname(vec1)
     #[1]  8 14 20 26 20 26 32 32 38 44

      

+4


source







All Articles