How to find the diagonal elements of a matrix?
<p>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:</p>
<pre><code>diagonal &lt;- function(x) {
  for (i in nrow(x)) {
    for (j in ncol(x)) {
      if (i == j) {
        a &lt;- x[i, j]
      }
    }
  }
  print(a)
}
</code></pre>
<p>I am passing a matrix to the function.
What is wrong with the code?</p>