1+ // File: src/main/java/com/thealgorithms/matrix/LUDecomposition.java
2+ package com .thealgorithms .matrix ;
3+
4+ import java .util .Arrays ;
5+
6+ /**
7+ * Implements the LU Decomposition algorithm for a square matrix.
8+ *
9+ * LU decomposition factors a matrix as the product of a lower triangular matrix (L)
10+ * and an upper triangular matrix (U). This implementation uses the Doolittle algorithm,
11+ * where the diagonal elements of the lower triangular matrix L are all 1s.
12+ */
13+ public class LUDecomposition {
14+
15+ /**
16+ * Decomposes a given square matrix into Lower (L) and Upper (U) matrices.
17+ *
18+ * @param matrix The square matrix to be decomposed.
19+ * @return An array containing L and U matrices. result[0] is L, result[1] is U.
20+ * @throws IllegalArgumentException if the matrix is not square.
21+ */
22+ public static double [][][] decompose (double [][] matrix ) {
23+ int n = matrix .length ;
24+ if (n == 0 || matrix [0 ].length != n ) {
25+ throw new IllegalArgumentException ("Matrix must be square." );
26+ }
27+
28+ double [][] lower = new double [n ][n ];
29+ double [][] upper = new double [n ][n ];
30+
31+ for (int i = 0 ; i < n ; i ++) {
32+ // Upper Triangular Matrix
33+ for (int k = i ; k < n ; k ++) {
34+ double sum = 0 ;
35+ for (int j = 0 ; j < i ; j ++) {
36+ sum += (lower [i ][j ] * upper [j ][k ]);
37+ }
38+ upper [i ][k ] = matrix [i ][k ] - sum ;
39+ }
40+
41+ // Lower Triangular Matrix
42+ for (int k = i ; k < n ; k ++) {
43+ if (i == k ) {
44+ lower [i ][i ] = 1 ; // Diagonal of L is 1
45+ } else {
46+ double sum = 0 ;
47+ for (int j = 0 ; j < i ; j ++) {
48+ sum += (lower [k ][j ] * upper [j ][i ]);
49+ }
50+ lower [k ][i ] = (matrix [k ][i ] - sum ) / upper [i ][i ];
51+ }
52+ }
53+ }
54+
55+ return new double [][][] {lower , upper };
56+ }
57+
58+ /**
59+ * A utility function to print a matrix.
60+ * @param matrix The matrix to be printed.
61+ */
62+ public static void printMatrix (double [][] matrix ) {
63+ for (double [] row : matrix ) {
64+ System .out .println (Arrays .toString (row ));
65+ }
66+ }
67+
68+ /**
69+ * Main method to demonstrate the LU Decomposition.
70+ * @param args Command-line arguments (not used).
71+ */
72+ public static void main (String [] args ) {
73+ double [][] matrix = {
74+ {2 , -1 , -2 },
75+ {-4 , 6 , 3 },
76+ {-4 , -2 , 8 }
77+ };
78+
79+ System .out .println ("Original Matrix:" );
80+ printMatrix (matrix );
81+
82+ double [][][] luMatrices = decompose (matrix );
83+ double [][] lower = luMatrices [0 ];
84+ double [][] upper = luMatrices [1 ];
85+
86+ System .out .println ("\n Lower Triangular Matrix (L):" );
87+ printMatrix (lower );
88+
89+ System .out .println ("\n Upper Triangular Matrix (U):" );
90+ printMatrix (upper );
91+ }
92+ }
0 commit comments