reverse method

Mat3 reverse([
  1. Mat3? target
])

reverse the matrix @param target Target matrix to save in. @return The solution x

Implementation

Mat3 reverse([Mat3? target]) {
  target ??= Mat3();
  // finalruct equations
  const nr = 3; // num rows
  const nc = 6; // num cols
  List<num> eqns = _reverseEqns;
  int i;
  int j;
  for (i = 0; i < 3; i++) {
    for (j = 0; j < 3; j++) {
      eqns[i + nc * j] = elements[i + 3 * j];
    }
  }
  eqns[3 + 6 * 0] = 1;
  eqns[3 + 6 * 1] = 0;
  eqns[3 + 6 * 2] = 0;
  eqns[4 + 6 * 0] = 0;
  eqns[4 + 6 * 1] = 1;
  eqns[4 + 6 * 2] = 0;
  eqns[5 + 6 * 0] = 0;
  eqns[5 + 6 * 1] = 0;
  eqns[5 + 6 * 2] = 1;

  // Compute right upper triangular version of the matrix - Gauss elimination
  int n = 3;

  final k = n;
  int np;
  const kp = nc; // num rows
  num p;
  for (; n > 0; n--) {
    i = k - n;
    if (eqns[i + nc * i] == 0) {
      // the pivot is null, swap lines
      for (j = i + 1; j < k; j++) {
        if (eqns[i + nc * j] != 0) {
          for (np = kp;np > 0;--np) {
            // do line( i ) = line( i ) + line( k )
            p = kp - np;
            eqns[p.toInt() + nc * i] += eqns[p.toInt() + nc * j];
          }
          break;
        }
      }
    }
    if (eqns[i + nc * i] != 0) {
      for (j = i + 1; j < k; j++) {
        final multiplier = eqns[i + nc * j] / eqns[i + nc * i];
        for (np = kp;np > 0;np--) {
          // do line( k ) = line( k ) - multiplier * line( i )
          p = kp - np;
          eqns[p.toInt() + nc * j] = p <= i ? 0 : eqns[p.toInt() + nc * j] - eqns[p.toInt() + nc * i] * multiplier;
        }
      }
    }
  }

  // eliminate the upper left triangle of the matrix
  for (i = 2; i > 0;i--) {
    for (j = i-1;j > 0;j--) {
      final multiplier = eqns[i + nc * j] / eqns[i + nc * i];
      for(np = nc;np > 0;np--){
        p = nc - np;
        eqns[p.toInt() + nc * j] = eqns[p.toInt() + nc * j] - eqns[p.toInt() + nc * i] * multiplier;
      }
    }
  }

  // operations on the diagonal
  for (i=2;i >0;i--) {
    final multiplier = 1 / eqns[i + nc * i];
    for (np = nc;np>0;np--) {
      p = nc - np;
      eqns[p.toInt() + nc * i] = eqns[p.toInt() + nc * i] * multiplier;
    }
  }

  for (i = 2;i >0;i--) {
    for (j= 2; j > 0;j--) {
      p = eqns[nr + j + nc * i];
      if (p.isNaN || p == double.infinity) {
        throw ('Could not reverse! A=[${toString()}]');
      }
      target.e(i, j, p.toDouble());
    }
  }

  return target;
}