Search code examples
rmatrixcontrolsstructurediagonal

Create a program that sums the diagonal of a matrix


I'm trying to create a program that sums the diagonal of a matrix that I've created. I used the code below but I don't understand whats wrong with the code I made.

a <- c(1, 2, 3) 
b <- c(3, 5, 6)

x <- matrix(a, b, nrow=3, ncol=3)
x

for (i in 1:nrow(x)) {
  for (j in 1:ncol(x)) {
    if (i=j) {
      diags[i, j] <- sum(x[i, j])
    }
  }
}

Solution

  • It's already great code! However, as was noted in comments, you were trying to sum a scalar when you probably thought you were summing a vector. You need to add the result of x[i, j] to a starting value which is of course zero. So first create diags with value zero and add the result to it in each iteration of the loop.

    Notes: for comparisons we use `==`, for assignment in function calls =, and for assignment in the script `<-`. Better use the seq functions such as seq_len(nrow(x)) instead of 1:nrow(x); yields at first glance the same, but has advantages e.g. if nrow(x) is zero.

    diags <- 0
    
    for (i in seq_len(nrow(x))) {
      for (j in seq_len(ncol(x))) {
        if (i == j) {
          diags <- diags + x[i, j]
        }
      }
    }
    diags
    # [1] 9
    

    Checking with the diag function.

    sum(diag(x))
    # [1] 9
    

    Data:

    I used a slightly different matrix, that isn't so symmetric and has more distinguishable values.

    x <- matrix(1:9 , nrow=4, ncol=3)