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}) {
// For non-square matrices, compute the pseudo-inverse directly
if (!isSquareMatrix()) {
return pseudoInverse();
}
try {
// First attempt: Try LU decomposition for efficiency (works for most well-conditioned matrices)
var lu = decomposition.luDecompositionDoolittle();
var identity = Matrix.eye(rowCount);
return lu.solve(identity);
} catch (e) {
// LU decomposition failed, continue to SVD
}
// Second attempt: Use SVD which is more robust for ill-conditioned matrices
try {
var svd = decomposition.singularValueDecomposition();
// Check condition number to determine if the matrix is numerically invertible
if (svd.conditionNumber > Complex(conditionThreshold)) {
// Matrix is ill-conditioned but we can still compute a regularized inverse
return _computeRegularizedInverse(svd, conditionThreshold);
}
// Standard SVD-based inverse
var identity = Matrix.eye(rowCount);
return svd.solve(identity);
} catch (e) {
// If all else fails, use the generalized pseudo-inverse approach
return pseudoInverse();
}
}