public SquareMatrix Inverse() { var matrix = Augment(Identity(Size)); matrix.MakeRowEchelon(); var squareMatrix = new SquareMatrix(Size); var squareMatrix2 = new SquareMatrix(Size); for (var i = 0; i < Size; i++) { squareMatrix.SetColumn(i, matrix.GetColumn(i)); squareMatrix2.SetColumn(i, matrix.GetColumn(i + Size)); } for (var j = 0; j < squareMatrix.Rows; j++) { if (squareMatrix.IsRowZero(j)) { throw new MatrixException("Matrix is singular"); } } for (var k = Size - 1; k > 0; k--) { for (var l = k - 1; l >= 0; l--) { var scalar = -squareMatrix[l, k]; squareMatrix.AddRowTimesScalar(l, k, scalar); squareMatrix2.AddRowTimesScalar(l, k, scalar); } } return squareMatrix2; }
public void LUDecomposition(out SquareMatrix l, out SquareMatrix u) { l = new SquareMatrix(Size); u = new SquareMatrix(Size); if (Math.Abs(base[0, 0] - 0.0) < 0.0001) { throw new MatrixException("Unable to decompose matrix"); } l.SetColumn(0, GetColumn(0)); u.SetRow(0, GetRow(0)); u.MultiplyRow(0, 1.0/base[0, 0]); for (var i = 1; i < Size; i++) { var array = new Vector[Size]; var array2 = new Vector[Size]; for (var j = 1; j < Size; j++) { array[j] = new Vector(i); array2[j] = new Vector(i); var row = l.GetRow(j); var column = u.GetColumn(j); for (var k = 0; k < i; k++) { array[j][k] = row[k]; array2[j][k] = column[k]; } } for (var m = i; m < Size; m++) { l[m, i] = base[m, i] - Vector.Dot(array[m], array2[i]); if (m == i) { u[i, m] = 1.0; } else { if (Math.Abs(l[i, i] - 0.0) < 0.0001) { throw new MatrixException("Unable to decompose matrix"); } u[i, m] = (base[i, m] - Vector.Dot(array[i], array2[m]))/l[i, i]; } } } }