inverse method

  1. @override
RealMatrix inverse()
override

Returns the inverse of this matrix.

The inverse of a square matrix A, sometimes called a reciprocal matrix, is a matrix A-1 such that "A A-1 = I" where I is the identity matrix.

A square matrix has an inverse if and only if the determinant isn't 0.

A MatrixException object is thrown if the matrix isn't square.

Implementation

@override
RealMatrix inverse() {
  if (!isSquareMatrix) {
    throw const MatrixException('The matrix must be square!');
  }

  // The inverse of an 1x1 matrix "A" is simply "1/A(0,0)"
  if (rowCount == 1) {
    return RealMatrix.fromFlattenedData(
      rows: 1,
      columns: 1,
      data: [1 / this(0, 0)],
    );
  }

  // In case of 2x2 matrix, we can directly compute it and save computational
  // time. Note that, from here, we're sure that this matrix is square so no
  // need to check both the row count and the col count.
  if (rowCount == 2) {
    final mult = 1 / (this(0, 0) * this(1, 1) - this(0, 1) * this(1, 0));

    return RealMatrix.fromFlattenedData(
      rows: 2,
      columns: 2,
      data: [
        mult * this(1, 1),
        -mult * this(0, 1),
        -mult * this(1, 0),
        mult * this(0, 0),
      ],
    );
  }

  // If the matrix to be inverted is 3x3 or greater, let's use the cofactor
  // method to compute the inverse. The inverse of a matrix can be computed
  // like so:
  //
  //   A^(-1) = 1 / det(A) * cof(A)^(T)
  //
  // where 'det(A)' is the determinant of A and 'cof(A)^T' is the transposed
  // matrix of the cofactor matrix.
  final transpose = cofactorMatrix().transpose();

  // Multiplying each number by 1/det(A)
  final multiplier = 1 / determinant();
  final inverse = transpose.flattenData
      .map((value) => multiplier * value)
      .toList(growable: false);

  return RealMatrix.fromFlattenedData(
    rows: rowCount,
    columns: columnCount,
    data: inverse,
  );
}