title: Is there an algorithm to multiply square matrices in-place?
body: <p>The naive algorithm for multiplying 4x4 matrices looks like this:</p>
  
  <pre class="lang-c prettyprint-override"><code>void matrix_mul(double out[4][4], double lhs[4][4], double rhs[4][4]) {
      for (int i = 0; i &lt; 4; ++i) {
          for (int j = 0; j &lt; 4; ++j) {
              out[i][j] = 0.0;
              for (int k = 0; k &lt; 4; ++k) {
                  out[i][j] += lhs[i][k] * rhs[k][j];
              }
          }
      }
  }
  </code></pre>
  
  <p>Obviously, this algorithm gives bogus results if <code>out == lhs</code> or <code>out == rhs</code> (here <code>==</code> means reference equality).  Is there a version that allows one or both of those cases that doesn't simply copy the matrix?  I'm happy to have different functions for each case if necessary.</p>
  
  <p>I found <a href="https://www.google.ca/search?q=winoschedule.pdf" rel="nofollow noreferrer">this</a> paper but it discusses the Strassen-Winograd algorithm which is overkill for my small matrices.  The answers to <a href="https://stackoverflow.com/q/1167852/502399">this</a> question seem to indicate that if <code>out == lhs &amp;&amp; out == rhs</code> (i.e., we're attempting to square the matrix), then it can't be done in place, but even there there's no convincing evidence or proof.</p>