inverse method
Calculates the inverse of a square matrix, falling back to SVD-based inversion or generalized pseudo-inversion if necessary.
This method first attempts regular matrix inversion using LU decomposition. If the matrix is near-singular or ill-conditioned (as determined by the condition number), it falls back to an inversion based on Singular Value Decomposition (SVD). If all else fails, it uses the pseudo-inverse as a generalized solution.
conditionThreshold
: A threshold for the condition number, above which the matrix is considered ill-conditioned. Default is1e-3
.
Throws:
Returns:
- A Matrix representing the inverse of the current matrix.
Example:
var matrix = Matrix([[1, 2], [3, 4]]);
var result = matrix.inverse();
print(result);
// Output:
// Matrix: 2x2
// ┌ -2.0 1.0 ┐
// └ 1.5 -0.5 ┘
Implementation
Matrix inverse({double conditionThreshold = 1e-3}) {
// if (rowCount != columnCount) {
// throw Exception('Matrix must be square to calculate inverse');
// }
// Compute SVD decomposition.
var svd = decomposition.singularValueDecomposition();
print('Condition number is: ${svd.conditionNumber}');
if (svd.conditionNumber > Complex(conditionThreshold)) {
print(
'Matrix condition number exceeds threshold $conditionThreshold. Likely singular.');
} else {
try {
// Attempt regular inversion using LU solve.
var lu = decomposition.luDecompositionDoolittle();
var identity = Matrix.eye(rowCount);
return lu
.solve(identity); // Solve A * X = I for X (generalized inverse).
} catch (e) {
print('Failed regular inversion: $e. Falling back to SVD inversion...');
}
}
// SVD Inversion.
try {
print('Attempting SVD inversion...');
// Identity matrix of the same size.
var identity = Matrix.eye(rowCount);
return svd.solve(identity);
} catch (e) {
print('SVD inversion failed: $e');
}
// Generalized Inverse Fallback.
print('Falling back to generalized inverse...');
return pseudoInverse();
}