Finding the LU decomposition of a matrix
Here’s an example Java program that performs LU decomposition of a matrix using the Doolittle algorithm:
public class LUDecomposition { public static void main(String[] args) { double[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 10} }; double[][][] lu = decompose(matrix); System.out.println("LU decomposition:"); System.out.println("L = "); printMatrix(lu[0]); System.out.println("U = "); printMatrix(lu[1]); } public static double[][][] decompose(double[][] matrix) { int n = matrix.length; double[][] L = new double[n][n]; double[][] U = new double[n][n]; // Perform LU decomposition for (int i = 0; i < n; i++) { // Compute L for (int j = 0; j < n; j++) { if (j < i) { L[j][i] = 0; } else if (j == i) { L[j][i] = 1; } else { double sum = 0; for (int k = 0; k < i; k++) { sum += L[j][k] * U[k][i]; } L[j][i] = matrix[j][i] - sum; } } // Compute U for (int j = 0; j < n; j++) { if (j < i) { U[i][j] = 0; } else { double sum = 0; for (int k = 0; k < i; k++) { sum += L[i][k] * U[k][j]; } U[i][j] = (matrix[i][j] - sum) / L[i][i]; } } } return new double[][][] { L, U }; } public static void printMatrix(double[][] matrix) { for (double[] row : matrix) { for (double value : row) { System.out.printf("%.2f ", value); } System.out.println(); } } }
This program decomposes a 3×3 matrix into its lower triangular matrix (L) and upper triangular matrix (U) components. The `decompose` method implements the Doolittle algorithm, which iteratively computes the entries of L and U based on the given matrix. The `printMatrix` method is used to display the matrices L and U.
When you run this program, you will see the L and U matrices printed in the console as output
No comments yet! You be the first to comment.