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?