'How to find the diagonal elements of a matrix?

I have written a function to store the diagonal elements of a matrix into a vector. but the output is not as I expected. The code is:

diagonal <- function(x) {
  for (i in nrow(x)) {
    for (j in ncol(x)) {
      if (i == j) {
        a <- x[i, j]
      }
    }
  }
  print(a)
}

I am passing a matrix to the function. What is wrong with the code?

r


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source