title: Get all diagonal vectors from matrix
body: <p>I'm trying to figure out how to get all the diagonals of a matrix.
  For example, say I have the following matrix:
  A &lt;- matrix(1:16,4)</p>
  
  <p>using the <code>diag(A)</code> function will return</p>
  
  <pre><code>[1]  1  6 11 16
  </code></pre>
  
  <p>In addition to the primary diagonal, I would like a list of all the diagonals above and below it.</p>
  
  <pre><code>5 10 15
  2  7 12
  9 14
  3  8
  4
  13
  </code></pre>
  
  <p>I found the following link <a href="https://stackoverflow.com/a/13049722">https://stackoverflow.com/a/13049722</a> which gives me the diagonals directly above and below the primary one, however I cannot seem to figure out how to extend the code to get the rest of them for any size matrix.  I tried two nested for loops since it appears that some kind of incrementing of the matrix subscripts would produce the result I am looking for.  I tried using ncol(A), nrow(A) in the for loops, but couldn't seem to figure out the right combination.  Plus I am aware that for loops are generally frowned upon in R.</p>
  
  <p>The code given was:</p>
  
  <pre><code>diag(A[-4,-1])
  diag(A[-1,-4])
  </code></pre>
  
  <p>which returned the two diagonals, both upper and lower</p>
  
  <p>Of course this is a square matrix and not all of the matrices I want to perform this on will be square.  Filling in the non-square area with NAs would be acceptable if necessary.  The answer I need may be in one of the other answers on the page, but the original question involved means, sums, etc. which added a layer of complexity beyond what I am trying to do.  I have a feeling the solution to this will be ridiculously simple, but it just isn't occurring to me.  I'm also surprised I was not able to find this question anywhere on SO, it would seem to be a common enough question.  Maybe I don't know the proper terminology for this problem.</p>