/// <summary> /// Recursive function for finding determinant of matrix. /// </summary> /// <param name="matrix">The matrix.</param> /// <returns></returns> /// <acknowledgment> /// https://www.geeksforgeeks.org/determinant-of-a-matrix/ /// https://www.geeksforgeeks.org/adjoint-inverse-matrix/ /// </acknowledgment> //[DisplayName("Determinant of Matrix.")] //[Description("Finds the Determinant of a Matrix.")] //[Acknowledgment("https://www.geeksforgeeks.org/determinant-of-a-matrix/", "https://www.geeksforgeeks.org/adjoint-inverse-matrix/")] //[SourceCodeLocationProvider] //[DebuggerStepThrough] //[MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Determinant1(double[,] matrix) { // This method is broken. It does not provide the correct values for anything over 2 rows. if (matrix is null) { throw new ArgumentNullException(nameof(matrix)); } var rows = matrix.GetLength(0); //var cols = matrix.GetLength(1); var result = 0d; // Initialize result // Base case : if matrix contains single element if (rows == 1) { return(matrix[0, 0]); } else if (rows == 2) { result = matrix[0, 0] * matrix[1, 1] - matrix[0, 1] * matrix[1, 0]; return(result); } var sign = 1d; // To store sign multiplier // Iterate for each element of first row for (var f = 0; f < rows; f++) { // Getting Cofactor of A[0,f] var temp = GeneralMatrixSparseCofactorTests.Cofactor(matrix, 0, f); result += sign * matrix[0, f] * Determinant(temp); // Terms are to be added with alternate sign sign = -sign; } return(result); }
public static double[,] Adjoint1(double[,] matrix) { if (matrix is null) { throw new ArgumentNullException(nameof(matrix)); } var rows = matrix.GetLength(0); var cols = matrix.GetLength(1); if (rows == 1) { return(new double[1, 1] { { 1d } }); } var adj = new double[rows, cols]; for (var i = 0; i < rows; i++) { for (var j = 0; j < cols; j++) { // Get cofactor of A[i,j] var temp = GeneralMatrixSparseCofactorTests.Cofactor(matrix, i, j); // Sign of adj[j,i] positive if sum of row and column indexes is even. var sign = ((i + j) % 2d == 0d) ? 1d : -1d; // Interchanging rows and columns to get the transpose of the cofactor matrix adj[j, i] = sign * GeneralMatrixDeterminantTests.Determinant(temp); } } return(adj); }