static/js/numeric.js
/**
 * Compute the inverse of a matrix.
 * @function matInv
 * @param {number[]} x - the input matrix
 * @return {number[]} inverse of the input matrix
 * @see {@link https://en.wikipedia.org/wiki/Invertible_matrix}
 * @see numpy.linalg.inv
 */
Compute the inverse of a matrix.
Compute the inverse of a matrix .
function matInv(x) {
  if (typeof(x) === 'number') {
    return 1 / x;
  }
  let r = x.length;
  let c = x[0].length;
  let a = [];
  for (let i = 0; i < r; i++) { 
    a[i] = x[i].slice();
  }
  let res = idMat(r);
  let k, Ii, Ij, temp;
  for (let i = 0; i < c; i++) {
    let idx = i;
    let max = a[i][i];
    for (let j = i; j < r; j++) {
      let cur = Math.abs(a[j][i]);
      if (cur > max) { 
        idx = j;
        max = cur;
      }
    }
    if (idx !== i) {
      temp = a[idx];
      a[idx] = a[i];
      a[i] = temp;
      temp = res[idx];
      res[idx] = res[i];
      res[i] = temp;
    }
    let Aj = a[i];
    let Ij = res[i];
    let f = Aj[i];
    for (let j = i; j < c; j++) {
      Aj[j] /= f;
    }
    for (let j = 0; j < c; j++) {
      Ij[j] /= f;
    }
    for (let j = 0; j < r; j++) {
      if (j !== i) {
        let Ai = a[j];
        Ii = res[j];
        f = Ai[i];
        for (k = i + 1; k < c; k++) {
          Ai[k] -= Aj[k] * f;
        }
        for (k = c - 1; k > 0; k--) {
          Ii[k] -= Ij[k] * f;
          k--;
          Ii[k] -= Ij[k] * f;
        }
        if (k===0) {
          Ii[0] -= Ij[0] * f;
        }
      }
    }
  }
  return res;
}
function matInv ( x ) { if ( typeof ( x ) === 'number' ) { return 1 / x ; } let r = x . length ; let c = x [ 0 ] . length ; let a = [ ] ; for ( let i = 0 ; i < r ; i ++ ) { a [ i ] = x [ i ] . slice ( ) ; } let res = idMat ( r ) ; let k , Ii , Ij , temp ; for ( let i = 0 ; i < c ; i ++ ) { let idx = i ; let max = a [ i ] [ i ] ; for ( let j = i ; j < r ; j ++ ) { let cur = Math . abs ( a [ j ] [ i ] ) ; if ( cur > max ) { idx = j ; max = cur ; } } if ( idx !== i ) { temp = a [ idx ] ; a [ idx ] = a [ i ] ; a [ i ] = temp ; temp = res [ idx ] ; res [ idx ] = res [ i ] ; res [ i ] = temp ; } let Aj = a [ i ] ; let Ij = res [ i ] ; let f = Aj [ i ] ; for ( let j = i ; j < c ; j ++ ) { Aj [ j ] /= f ; } for ( let j = 0 ; j < c ; j ++ ) { Ij [ j ] /= f ; } for ( let j = 0 ; j < r ; j ++ ) { if ( j !== i ) { let Ai = a [ j ] ; Ii = res [ j ] ; f = Ai [ i ] ; for ( k = i + 1 ; k < c ; k ++ ) { Ai [ k ] -= Aj [ k ] * f ; } for ( k = c - 1 ; k > 0 ; k -- ) { Ii [ k ] -= Ij [ k ] * f ; k -- ; Ii [ k ] -= Ij [ k ] * f ; } if ( k === 0 ) { Ii [ 0 ] -= Ij [ 0 ] * f ; } } } } return res ; }
Compute the inverse of a matrix.
Compute the inverse of a matrix .
// deep copy the input array // row reduction // find max element and its index in the ith column // row exchange // eleminate non-zero values on other rows at column c