cofactorMatrix method

  1. @override
RealMatrix cofactorMatrix()
override

The matrix formed by all of the cofactors of a square matrix is called the "cofactor matrix" (also called "the matrix of cofactors").

In practice, this matrix is obtained by calling minor(i, j) for all the rows and columns combinations of the matrix.

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

Implementation

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

  // The cofactor matrix of an 1x1 matrix is always 1.
  if (rowCount == 1) {
    return RealMatrix.fromFlattenedData(
      rows: 1,
      columns: 1,
      data: [1],
    );
  }

  final source = List<List<double>>.generate(
    rowCount,
    (_) => List<double>.generate(columnCount, (_) => 0.0),
  );

  // Computing cofactors.
  for (var i = 0; i < rowCount; ++i) {
    for (var j = 0; j < columnCount; ++j) {
      source[i][j] = pow(-1, i + j) * minor(i, j).determinant();
    }
  }

  return RealMatrix.fromData(
    rows: rowCount,
    columns: columnCount,
    data: source,
  );
}