Finding the matrix determinant using Gaussian elimination.
Here’s a Java program that calculates the determinant of a matrix using Gaussian elimination:
public class MatrixDeterminant { public static double findDeterminant(double[][] matrix) { int n = matrix.length; if (n == 1) { return matrix[0][0]; } double determinant = 1; for (int i = 0; i < n; i++) { if (matrix[i][i] == 0) { swapRows(matrix, i); determinant *= -1; } for (int j = i + 1; j < n; j++) { double factor = matrix[j][i] / matrix[i][i]; for (int k = i; k < n; k++) { matrix[j][k] -= factor * matrix[i][k]; } } determinant *= matrix[i][i]; } return determinant; } private static void swapRows(double[][] matrix, int row) { int n = matrix.length; for (int i = row + 1; i < n; i++) { if (matrix[i][row] != 0) { for (int j = 0; j < n; j++) { double temp = matrix[i][j]; matrix[i][j] = matrix[row][j]; matrix[row][j] = temp; } return; } } } public static void main(String[] args) { double[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; double determinant = findDeterminant(matrix); System.out.println("Matrix:"); for (double[] row : matrix) { for (double element : row) { System.out.print(element + " "); } System.out.println(); } System.out.println("Determinant: " + determinant); } }
In this program, the `findDeterminant` method accepts a 2D array representing the matrix and returns its determinant. The algorithm used is Gaussian elimination, where the matrix is transformed into an upper triangular matrix by performing row operations.
The `swapRows` method is a helper function that swaps rows if the pivot element is zero, to avoid division by zero.
In the `main` method, a sample matrix is defined, and its determinant is calculated using the `findDeterminant` method. The matrix and its determinant are then printed to the console.
Note that this implementation assumes the input matrix is square. You can modify the program to handle rectangular matrices if needed.