cofactorMatrix method

  1. @override
ComplexMatrix 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.

Implementation

@override
ComplexMatrix 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 ComplexMatrix.fromFlattenedData(
      rows: 1,
      columns: 1,
      data: const [
        Complex.fromReal(1),
      ],
    );
  }

  final source = List<List<Complex>>.generate(rowCount, (_) {
    return List<Complex>.generate(columnCount, (_) => const Complex.zero());
  });

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

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