public double[,] Inverse()
{
if (!Nonsingular)
{
throw new InvalidOperationException("Matrix is singular");
}
int rows = lu.GetLength(1);
int columns = lu.GetLength(1);
int count = rows;
// Copy right hand side with pivoting
var X = new double[rows,columns];
for (int i = 0; i < rows; i++)
{
int k = pivotVector[i];
X[i, k] = 1.0;
}
// Solve L*Y = B(piv,:)
for (int k = 0; k < columns; k++)
for (int i = k + 1; i < columns; i++)
for (int j = 0; j < count; j++)
X[i, j] -= X[k, j]*lu[i, k];
// Solve U*X = I;
for (int k = columns - 1; k >= 0; k--)
{
for (int j = 0; j < count; j++)
X[k, j] /= lu[k, k];
for (int i = 0; i < k; i++)
for (int j = 0; j < count; j++)
X[i, j] -= X[k, j]*lu[i, k];
}
return X;
}