/// <summary> /// Optimized version of Determinant, that only uses double[,] /// </summary> /// <param name="array">Matrix array to compute</param> /// <param name="scalar">The scalar.</param> /// <returns> /// Determinant of the matrix /// </returns> /// <acknowledgment> /// https://github.com/PigDogBay/MpdbSharedLibrary/blob/master/MpdbSharedLibrary/Maths/Matrix.cs /// </acknowledgment> private static double Determinant3(double[,] array, double scalar = 1) { var rows = array.GetLength(0); if (rows == 1) { return(array[0, 0]); } else if (rows == 2) { return((array[0, 0] * array[1, 1] - array[0, 1] * array[1, 0]) * scalar * scalar); } double det = 0; // Get minors and recurse down for (var i = 0; i < rows; i++) { // Get the minor var minor = GeneralGetMatrixMinorTests.GetMinor(array, i, 0); // Find correct sign if (i % 2 == 0) { det += Determinant3(minor, scalar) * array[0, i] * scalar; } else { det -= Determinant3(minor, scalar) * array[0, i] * scalar; } } return(det); }
/// <summary> /// The co-factor is the determinant of the matrix that remains when the row and column containing the /// specified element is removed. The co-factor may also be multiplied by -1, depending on the element's position: /// + - + - /// - + - + /// + - + - /// </summary> /// <param name="matrix">The matrix.</param> /// <param name="col">column number (starting at 0)</param> /// <param name="row">row number (starting at 0)</param> /// <returns> /// The cofactor of the specified element /// </returns> /// <exception cref="InvalidOperationException">Matrix must have the same number of rows and columns for the co-factor to be calculated</exception> public static double CoFactor1(double[,] matrix, int col, int row) { var rows = matrix.GetLength(0); var cols = matrix.GetLength(1); if (cols != rows) { throw new InvalidOperationException("Matrix must have the same number of rows and columns for the co-factor to be calculated"); } var array = GeneralGetMatrixMinorTests.GetMinor(matrix, col, row); var cofactor = GeneralMatrixDeterminantTests.Determinant(array); // need to work out sign: var i = col - row; if ((i % 2) != 0) { cofactor = -cofactor; } return(cofactor); }