nullSpace method

Matrix nullSpace()

Returns the null space (also known as kernel) of the matrix.

The null space is the linear space formed by all vectors that, when multiplied by the matrix, result in the zero vector.

Example:

Matrix A = Matrix.fromList([
  [1, 2, 3],
  [0, 1, 1],
  [0, 0, 0]
]);
print(A.nullSpace());
// Output:
// -2
//  3
//  0

Implementation

Matrix nullSpace() {
  Matrix rref = reducedRowEchelonForm();
  int freeVarCount = rref.columnCount - rref.rank();

  if (freeVarCount > 0) {
    List<List<double>> nullSpace = [];
    for (int i = 0; i < freeVarCount; i++) {
      List<double> nullSpaceVector = List.filled(rref.columnCount, 0.0);
      int freeVarIndex = rref.columnCount - freeVarCount + i;

      for (int j = 0; j < rref.rowCount; j++) {
        int pivotPosition = rref[j].lastIndexOf(
            rref[j][freeVarIndex]); // Find last index of the value
        if (rref[j][freeVarIndex] != 0 && pivotPosition == freeVarIndex) {
          nullSpaceVector[j] = -rref[j][freeVarIndex];
        }
      }

      nullSpaceVector[freeVarIndex] = 1;
      nullSpace.add(nullSpaceVector);
    }

    return Matrix(nullSpace);
  } else {
    //throw Exception('The matrix has no null space.');
    return Matrix();
  }
}