title: Most efficient way to loop through an Eigen matrix
body: <p>I'm creating some functions to do things like the "separated sum" of negative and positive number, kahan, pairwise and other stuff where it doesn't matter the order I take the elements from the matrix, for example:</p>
  
  <pre><code>template &lt;typename T, int R, int C&gt;
  inline T sum(const Eigen::Matrix&lt;T,R,C&gt;&amp; xs)
  {
    T sumP(0);
    T sumN(0);
    for (size_t i = 0, nRows = xs.rows(), nCols = xs.cols(); i &lt; nRows; ++i)
     for (size_t j = 0; j &lt; nCols; ++j)
     {
          if (xs(i,j)&gt;0)
            sumP += xs(i,j);
          else if (xs(i,j)&lt;0) //ignore 0 elements: improvement for sparse matrices I think
            sumN += xs(i,j);
     }
   return sumP+sumN;
  }
  </code></pre>
  
  <p>Now, I would like to make this as efficient as possible, so my question is, would it be better to loop through each column of each row like the above, or do the opposite like the the following:</p>
  
  <pre><code>for (size_t i = 0, nRows = xs.rows(), nCols = xs.cols(); i &lt; nCols; ++i)
    for (size_t j = 0; j &lt; nRows; ++j)
  </code></pre>
  
  <p>(I suppose this depends on the order that the matrix elements are allocated in memory, but I couldn't find this in Eigen's manual).</p>
  
  <p>Also, are there other alternate ways like using iterators (do they exist in Eigen?) that might be slightly faster?</p>