Finding the inverse of a matrix.
Here’s an example of a Java program that finds the inverse of a matrix using the Gauss-Jordan elimination method:
import java.util.Arrays; public class MatrixInverse { public static double[][] findInverse(double[][] matrix) { int n = matrix.length; double[][] augmentedMatrix = new double[n][2 * n]; // Create an augmented matrix by appending an identity matrix for (int i = 0; i < n; i++) { System.arraycopy(matrix[i], 0, augmentedMatrix[i], 0, n); augmentedMatrix[i][i + n] = 1; } // Apply Gauss-Jordan elimination for (int i = 0; i < n; i++) { // Pivot for the current row double pivot = augmentedMatrix[i][i]; // Divide the current row by the pivot for (int j = 0; j < 2 * n; j++) { augmentedMatrix[i][j] /= pivot; } // Eliminate other rows for (int j = 0; j < n; j++) { if (j != i) { double factor = augmentedMatrix[j][i]; for (int k = 0; k < 2 * n; k++) { augmentedMatrix[j][k] -= factor * augmentedMatrix[i][k]; } } } } // Extract the inverse matrix from the augmented matrix double[][] inverseMatrix = new double[n][n]; for (int i = 0; i < n; i++) { System.arraycopy(augmentedMatrix[i], n, inverseMatrix[i], 0, n); } return inverseMatrix; } public static void main(String[] args) { double[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; double[][] inverse = findInverse(matrix); System.out.println("Original Matrix:"); printMatrix(matrix); System.out.println("Inverse Matrix:"); printMatrix(inverse); } public static void printMatrix(double[][] matrix) { for (double[] row : matrix) { System.out.println(Arrays.toString(row)); } System.out.println(); } }
This program defines a `findInverse` method that takes a square matrix as input and returns its inverse. The `main` method demonstrates the usage of the `findInverse` method by finding the inverse of a 3×3 matrix and printing both the original matrix and its inverse.
Note that this implementation assumes the input matrix is non-singular (i.e., it has an inverse). Additionally, it is always good practice to add additional error checking and validation for real-world applications.
No comments yet! You be the first to comment.