title: Eigen Sparse matrix. Sorting non-zero elements with respect to rows
body: <p>I have a sparse matrix and I need to store the non-zero elements and respective row,column in ascending order with respect to rows</p>
  
  <p>following this <a href="https://eigen.tuxfamily.org/dox/group__TutorialSparse.html" rel="nofollow noreferrer">https://eigen.tuxfamily.org/dox/group__TutorialSparse.html</a>
  I tried </p>
  
  <pre><code>// mat =
  // 1.0, 0.0, 1.0, 0.0, 0.0
  // 1.0, 0.0, 0.0, 0.0, 1.0
  // 0.0, 1.0, 0.0, 0.0, 0.0
  // 0.0, 0.0, 1.0, 0.0, 1.0
  // 1.0, 0.0, 0.0, 1.0, 0.0 
  
  // create and fill the sparse matrix
  SparseMatrix&lt;double&gt; mat(5,5);
  mat.insert(0,0) = 1.0;
  mat.insert(0,2) = 1.0;
  mat.insert(1,0) = 1.0;
  mat.insert(1,4) = 1.0;
  mat.insert(2,1) = 1.0;
  mat.insert(3,2) = 1.0;
  mat.insert(3,4) = 1.0;
  mat.insert(4,0) = 1.0;
  mat.insert(4,3) = 1.0;
  
  //matrix where to store the row,col,value
  Eigen::MatrixXd mat_map(mat.nonZeros(),3);
  
  int index_mat;
  index_mat=-1;
  
  for (int k=0; k&lt;mat.outerSize(); ++k)
    for (SparseMatrix&lt;double&gt;::InnerIterator it(mat,k); it; ++it)
     {
       index_mat++;
       mat_map(index_mat,0) = it.row();   // row index
       mat_map(index_mat,1) = it.col();   // col index 
       mat_map(index_mat,2) = it.value();
     }
  
  
  cout &lt;&lt; mat_map &lt;&lt; endl;
  </code></pre>
  
  <p>what I get is the following </p>
  
  <pre><code>0 0 1.0
  1 0 1.0
  4 0 1.0
  2 1 1.0
  0 2 1.0
  3 2 1.0
  4 3 1.0
  1 4 1.0
  3 4 1.0
  </code></pre>
  
  <p>while what I want is</p>
  
  <pre><code>0 0 1.0
  0 2 1.0 
  1 0 1.0
  1 4 1.0
  2 1 1.0  
  3 2 1.0
  3 4 1.0
  4 0 1.0
  4 3 1.0
  </code></pre>
  
  <p>Any help will be appreciated</p>
  
  <p>thanks!</p>