/// <summary> /// Calculates and returns the adjunct for the specified matrix /// </summary> /// <param name="matrix">The matrix</param> /// <returns>The adjunct matrix</returns> public static int[,] Adjunct(int[,] matrix) { if (!MatrixHelper.IsMatrixValid(matrix)) { return(new int[0, 0]); } int rows = matrix.GetLength(0), cols = matrix.GetLength(1); if (rows != cols) { Console.WriteLine("The matrix is not square"); return(new int[0, 0]); } int[,] transpose = MatrixHelper.Transpose(matrix); if (!MatrixHelper.IsMatrixValid(transpose)) { return(new int[0, 0]); } int rowsTranspose = transpose.GetLength(0), colsTranspose = transpose.GetLength(1); int[,] adjunct = new int[rowsTranspose, colsTranspose]; for (int i = 0; i < rowsTranspose; i++) { for (int j = 0; j < colsTranspose; j++) { int sign = ((i + j) % 2 == 0) ? 1 : -1; int minor = MatrixHelper.Determinant(MatrixHelper.RemoveRowAndColumn(transpose, i, j)); adjunct[i, j] = sign * minor; } } return(adjunct); }
/// <summary> /// Calculates the determinant of a square (n X n) matrix /// using a recursive implementation of the Laplace expansion calculation method /// </summary> /// <param name="squareMatrix">The square (n X n) matrix</param> /// <returns>The determinant value</returns> public static int Determinant(int[,] squareMatrix) { // Uses Laplace expansion // Inspiration came from: http://www.mathsisfun.com/algebra/matrix-determinant.html // See also: https://en.wikipedia.org/wiki/Laplace_expansion if (!MatrixHelper.IsMatrixValid(squareMatrix)) { return(0); } int rows = squareMatrix.GetLength(0), cols = squareMatrix.GetLength(1); if (rows != cols) { Console.WriteLine("The matrix is not square"); return(0); } if (rows == 1) { return(MatrixHelper.DeterminantMatrix1_1(squareMatrix)); } else if (rows == 2) { return(MatrixHelper.DeterminantMatrix2_2(squareMatrix)); } else { int det = 0; for (int i = 0; i < cols; i++) { int sign = (i % 2 == 0) ? 1 : (-1); det += sign * squareMatrix[0, i] * MatrixHelper.Determinant(MatrixHelper.RemoveRowAndColumn(squareMatrix, 0, i)); } return(det); } }