public static decimal[,] Solve(this decimal[,] matrix, decimal[,] rightSide, bool leastSquares = false)
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
if (rows != rightSide.GetLength(0))
throw new DimensionMismatchException("rightSide",
"The number of rows in the right hand side matrix must be "
+ "equal to the number of rows in the problem matrix.");
if (leastSquares)
{
return new SingularValueDecompositionD(matrix,
computeLeftSingularVectors: true,
computeRightSingularVectors: true,
autoTranspose: true).Solve(rightSide);
}
if (rows == cols)
{
// Solve by LU Decomposition if matrix is square.
return new LuDecompositionD(matrix).Solve(rightSide);
}
else
{
if (cols < rows)
{
// Solve by QR Decomposition if not.
return new QrDecompositionD(matrix).Solve(rightSide);
}
else
{
return new SingularValueDecompositionD(matrix,
computeLeftSingularVectors: true,
computeRightSingularVectors: true,
autoTranspose: true).Solve(rightSide);
}
}
}