title: Returning a 2D vector
body: <p>I am writing a simple C++ program to do a kronecker tensor product of two matrices like the matlab function <a href="http://www.mathworks.com/help/matlab/ref/kron.html" rel="nofollow">kron</a></p>
  
  <p>Here is the program:</p>
  
  <pre><code>#include&lt;iostream&gt;
  #include&lt;vector&gt;
  
  using namespace std;
  
  vector&lt; vector&lt;double&gt; &gt; kron(vector&lt; vector&lt;double&gt; &gt; &amp;A, vector&lt; vector&lt;double&gt; &gt; &amp;B);
  
  int main()
  {
  
  
      vector&lt; vector&lt;double&gt; &gt; a = {{1,-2},{-1,0}}; // matrices a and b
      vector&lt; vector&lt;double&gt; &gt; b = {{4,-3},{2,3}};
  
      int m = a.size()*b.size();
      int n = a[0].size()*b[0].size();
  
      vector&lt; vector&lt;double&gt; &gt; T(m,vector&lt;double&gt;(n,0.0));
  
      T = kron(a,b);
  
  
      // Display the resulting matrix T
      for(int i  = 0; i &lt; T.size(); i++)
      {
          for(int j = 0; j &lt; T[0].size(); j++)
          {
              cout &lt;&lt; T[i][j] &lt;&lt; ",";
          }
  
          cout &lt;&lt; endl;
      }
  
  
      return 0;
  }
  
  vector&lt; vector&lt;double&gt; &gt; kron(vector&lt; vector&lt;double&gt; &gt; &amp;A, vector&lt; vector&lt;double&gt; &gt; &amp;B)
  {
      int krnProdRow = A.size()*B.size();
      int krnProdCol = A[0].size()*B[0].size();
      int nRowA = A.size();
      int nColA = A[0].size();
      int nRowB = B.size();
      int nColB = B[0].size();
  
      vector&lt; vector&lt;double&gt; &gt; krnProd(krnProdRow,vector&lt;double&gt;(krnProdCol,0.0));
  
      int i,j,k,l;
  
      for(i=0; i&lt;nRowA; i++)
      {
          for(k=0; k&lt;nRowB; k++)
          {
              for(j=0; j&lt;nColA ; j++)
              {
                  for(l=0; l&lt;nColB; l++)
                  {
                      krnProd[i+l+1][j+k+1] = A[i][j]*B[k][l];
                                  //cout &lt;&lt; krnProd[i+l+1][j+k+1] &lt;&lt; ",";
                  }
              }
              //cout &lt;&lt; endl;;
          }
      }
  
      return krnProd;
  }
  </code></pre>
  
  <p>When returning the matrix krnProd from the function and assigning it to the T matrix in my main function, I get the following matrix:</p>
  
  <pre><code>0, 0, 0, 0
  0, 4, 2, -4
  0, -4, -2, 0
  0, 3, -3, 0
  </code></pre>
  
  <p>which is totally wrong.</p>
  
  <p>However, if i print out the krnProd matrix inside the function itself, I get:</p>
  
  <pre><code>4, -3, -8, 6
  2, 3, -4, -6
  -4, 3, 0, 0
  -2, -3, 0, 0
  </code></pre>
  
  <p>which happens to be the true answer. I was wondering, why am I getting a different answer when returning the matrix from the function ? did i overlooked something here ? or the way I am returning the 2D vector is wrong ?</p>