/// <summary> /// Produces the determinant of a square matrix /// </summary> /// <param name="mat">The matrix</param> /// <returns>The determinant of the matrix</returns> public static T Determinant <T>(this T[,] mat) { MatrixDimensions d = mat.GetDimensions(); if (d.IsSquare()) { switch (d.rows) { case 0: throw new MatrixSizeException("A matrix cannot have no elements."); case 1: return(mat[0, 0]); case 2: return(mat[0, 0] * (dynamic)mat[1, 1] - mat[0, 1] * (dynamic)mat[1, 0]); default: T sum = mat[0, 0] * (dynamic)(mat.RemoveVector(VectorDirection.Row, 1).RemoveVector(VectorDirection.Column, 1).Determinant()); for (int i = 1; i < d.rows; i++) { if (i % 2 == 0) { sum += mat[0, i] * (dynamic)(mat.RemoveVector(VectorDirection.Row, 1).RemoveVector(VectorDirection.Column, i + 1).Determinant()); } else { sum -= mat[0, i] * (dynamic)(mat.RemoveVector(VectorDirection.Row, 1).RemoveVector(VectorDirection.Column, i + 1).Determinant()); } } return(sum); } } throw new IllegalOperationException("Only squre matricies have determinants."); }
/// <summary> /// Calculates the inverse of a matrix, if it has one /// </summary> /// <param name="matrix">The matrix</param> /// <returns>The matrix's inverse</returns> public static T[,] Inverse <T>(this T[,] matrix) { MatrixDimensions d = matrix.GetDimensions(); if (!d.IsSquare()) { throw new MatrixSizeException("A non-square matrix cannot have an inverse."); } T[][,] aug = matrix.Augment(Matrix <T> .IdentityMatrix(d.cols)).RREF().Separate(d.cols, d.cols); if (!aug[0].IsIdentity()) { throw new IllegalOperationException("A matrix with no identity has no inverse."); } return(aug[1]); }