Javascript Array invertMatrix(matrix)

Description

Javascript Array invertMatrix(matrix)


/*//  w  w w  . j a v  a  2 s .c  om
 * invertMatrix
 * Returns the inverse of a given NxN matrix
 * @matrix  Matrix to inverse (NxN array)
 * @return  Inverse of @matrix (NxN array)
 */

var invertMatrix = function (matrix) {
  var ratio, a;
  var i, j, k;
  var n = matrix.length;
  var invMatrix = matrix;
  for ( i = 0; i < n; i++ ) {
    for ( j = n; j < 2*n; j++ )
      invMatrix[i][j] = ( i == (j-n) ) ? 1.0 : 0.0;
  }
  for ( i = 0; i < n; i++ ) {
    for ( j = 0; j < n; j++ ) {
      if ( i != j ) {
        ratio = invMatrix[j][i]/invMatrix[i][i];
        for (k = 0; k < 2*n; k++ ) 
          invMatrix[j][k] -= ratio * invMatrix[i][k];
      }
    }
  }
  for ( i = 0; i < n; i++ ) {
    a = invMatrix[i][i];
    for ( j = 0; j < 2*n; j++ )
      invMatrix[i][j] /= a;
  }
  for ( i = 0; i < n; i++ )
    invMatrix[i].splice(0,n);
  return invMatrix;
};



PreviousNext

Related