/// <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 Determinant2(double[][] array, double scalar = 1) { var length = array.GetLength(0); if (length == 1) { return(array[0][0]); } else if (length == 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 < length; i++) { // get the minor var minor = JaggedGetMatrixMinorTests.GetMinor(array, i, 0); // find correct sign if (i % 2 == 0) { det += Determinant2(minor, scalar) * array[0][i] * scalar; } else { det -= Determinant2(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.Length; var cols = matrix[0].Length; 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 = JaggedGetMatrixMinorTests.GetMinor(matrix, col, row); var cofactor = JaggedMatrixDeterminantTests.Determinant(array); // need to work out sign: var i = col - row; if ((i % 2) != 0) { cofactor = -cofactor; } return(cofactor); }