title: Declare and initialize a map type matrix separately in EIGEN
body: <p>I am trying to use Eigen:Map with Stride to map two matrices to an array. For example, if </p>
  
  <pre><code>arr = {1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13 ,14 ,15 ,16 ,17 ,18 ,19 ,20 ,21 ,22 ,23 ,24} 
  </code></pre>
  
  <p>I want the mapped matrices to be</p>
  
  <pre><code>mat1 = {1, 7, 13, 19;
          3, 9, 15, 21;
          5, 11, 17, 23}
  </code></pre>
  
  <p>and</p>
  
  <pre><code>mat2 = {2, 8, 14, 20; 
          4, 10, 16, 22;
          6, 12, 18, 24}
  </code></pre>
  
  <p>The following code works:</p>
  
  <pre><code>int nmat = 2;        // number of matrices
  int nrow = 3;        // number of rows for each matrix
  int ncol = 4;        // number of columns for each matrix
  int arr_size = nmat*nrow*ncol; // size of the array.
  
  int *arr = new int[arr_size];
  
  Map&lt;MatrixXi, 0, Stride&lt;Dynamic, Dynamic&gt; &gt; mat1(arr ,nrow, ncol, Stride&lt;Dynamic,Dynamic&gt;(nrow*nmat, nmat));
  Map&lt;MatrixXi, 0, Stride&lt;Dynamic, Dynamic&gt; &gt; mat2(arr+1 ,nrow, ncol, Stride&lt;Dynamic,Dynamic&gt;(nrow*nmat, nmat));
  
  for (int i=0; i&lt;arr_size; i++) {
    arr[i] = i+1;
  }
  
  cout &lt;&lt;"mat1 = \n"&lt;&lt;mat1&lt;&lt;endl;
  cout &lt;&lt;"mat2 = \n"&lt;&lt;mat2&lt;&lt;endl;
  </code></pre>
  
  <p>The results are:</p>
  
  <pre><code>mat1 = 
  1  7 13 19
  3  9 15 21
  5 11 17 23
  mat2 = 
  2  8 14 20
  4 10 16 22
  6 12 18 24
  </code></pre>
  
  <p>However, I would like to declare and map the matrices separately like the following code:</p>
  
  <pre><code>MatrixXi mat1;
  MatrixXi mat2;
  new(&amp;mat1) Map&lt;MatrixXi, 0, Stride&lt;Dynamic, Dynamic&gt; &gt; (arr ,nrow, ncol, Stride&lt;Dynamic,Dynamic&gt;(nrow*nmat, nmat));
  new(&amp;mat2) Map&lt;MatrixXi, 0, Stride&lt;Dynamic, Dynamic&gt; &gt; (arr+1 ,nrow, ncol, Stride&lt;Dynamic,Dynamic&gt;(nrow*nmat, nmat));
  </code></pre>
  
  <p>This will give me Segmentation fault.</p>
  
  <p>If I comment out mat2 like the code below:</p>
  
  <pre><code>MatrixXi mat1;
  //  MatrixXi mat2;
  new(&amp;mat1) Map&lt;MatrixXi, 0, Stride&lt;Dynamic, Dynamic&gt; &gt; (arr ,nrow, ncol, Stride&lt;Dynamic,Dynamic&gt;(nrow*nmat, nmat));
  //  new(&amp;mat2) Map&lt;MatrixXi, 0, Stride&lt;Dynamic, Dynamic&gt; &gt; (arr+1 ,nrow, ncol, Stride&lt;Dynamic,Dynamic&gt;(nrow*nmat, nmat));
  </code></pre>
  
  <p>Then there is no Segmentation fault, but the Stride is not working. The results are:</p>
  
  <pre><code>mat1 = 
  1  4  7 10
  2  5  8 11
  3  6  9 12
  </code></pre>
  
  <p>The reason I want to separate the declaration and initialization is that I want to write a class which mat1 and mat2 are members of it. </p>