title: Matrix "Zigzag" Reordering
body: <p>I have an NxM matrix in MATLAB that I would like to reorder in similar fashion to the way JPEG reorders its subblock pixels:</p>
  
  <p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/JPEG_ZigZag.svg/220px-JPEG_ZigZag.svg.png" alt="zigzag layout pattern"> <sup><sup><a href="http://en.wikipedia.org/wiki/JPEG" rel="nofollow noreferrer">(image from Wikipedia)</a></sup></sup></p>
  
  <p>I would like the algorithm to be generic such that I can pass in a 2D matrix with any dimensions. I am a C++ programmer by trade and am very tempted to write an old school loop to accomplish this, but I suspect there is a better way to do it in MATLAB.</p>
  
  <p>I'd be rather want an algorithm that worked on an <code>NxN</code> matrix and go from there.</p>
  
  <h3>Example:</h3>
  
  <pre><code>1 2 3
  4 5 6  --&gt;  1 2 4 7 5 3 6 8 9
  7 8 9
  </code></pre>