javascriptmathmatrixinversion

How do I solve inverse of 3x3 matrices without using a library?


 <html>
<head>
  <script language="JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.2.1/math.js"></script>
</head>
<body>
  <p id="result">loading result...</p>
  <script> 
   var inverted = math.inv([[1,2,4],[3,4,5],[7,8,9]]);
  document.getElementById("result").textContent = JSON.stringify(inverted);
  </script>
</body>
</html>

This is what I have using math.js but I'm curious as to how i can do this without using a library.


Solution

  • Make sure matrix is "full" as in: no missing values.
    The following code works on matrices with row count!=column count as well.

    var originalMatrix=[[1,2,3],[4,5,6],[7,8,9]];
    function invertMatrix(matrix) {
      return matrix.reduce(
        (acc, cv)=> {
          cv.reduce(
            (acc2, cv2, idx2)=> {
              if(acc[idx2]==undefined) acc[idx2]=[];
              acc[idx2].push(cv2);
            },[]
          );
          return acc;
        },[]
      );
    };
    
    console.log(originalMatrix);
    console.log(invertMatrix(originalMatrix));
    console.log(invertMatrix(invertMatrix(originalMatrix)));
    
    var anotherMatrix=[[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]];
    
    console.log(anotherMatrix);
    console.log(invertMatrix(anotherMatrix));
    console.log(invertMatrix(invertMatrix(anotherMatrix)));
    .as-console-wrapper { max-height: 100% !important; top: 0; }