title: C++ PCA - Calculating covariance MATRIX
body: <p>I'm trying to calculate the Covariance (matrix) of a vector in C++ ... </p>
  
  <p>I have carried out the following:</p>
  
  <pre><code>std::vector&lt;std::vector&lt;double&gt; &gt; data = { {2.5, 2.4}, {0.5, 0.7} };
  </code></pre>
  
  <p>I have then calculated and subtracted the mean, which gave the following result:</p>
  
  <pre><code>data = { {0.05, -0.05}, {-0.1, 0.1} }
  </code></pre>
  
  <p>As far as I'm aware, the next step is to transpose the matrix, and multiply the origin together, take the sum and finally divide by the dimensions X - 1.. </p>
  
  <p>I have written the following:</p>
  
  <pre><code>void cover(std::vector&lt;std::vector&lt;double&gt; &gt; &amp;d)
  {
      double cov = 0.0; 
  
      for(unsigned i=0; (i &lt; d.size()); i++)
      {
          for(unsigned j=0; (j &lt; d[i].size()); j++)
          {
              cov += d[i][j] * d[j][i] / (d[i].size() - 1);
              std::cout &lt;&lt; cov &lt;&lt; " ";
          }
          std::cout &lt;&lt; std::endl;
      }
  }
  </code></pre>
  
  <p>Where <code>d</code> is the vector after the mean has been subtracted from each of the points 
  Which gives me the result:</p>
  
  <pre><code>0.0025, 0.0075 
  0.0125, 0.0225
  </code></pre>
  
  <p>Where compared with matlab:</p>
  
  <pre><code>2.0000    1.7000
  1.7000    1.4450
  </code></pre>
  
  <p>Does anyone have any ideas to where I am going wrong?</p>
  
  <p>Thanks</p>