Finding the QR decomposition of a matrix
Here’s an example of a Java program that finds the QR decomposition of a matrix using the Householder transformation method:
import java.util.Arrays; public class QRDecomposition { public static void main(String[] args) { double[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; double[][][] qr = decomposeQR(matrix); double[][] q = qr[0]; double[][] r = qr[1]; System.out.println("Matrix Q:"); printMatrix(q); System.out.println("Matrix R:"); printMatrix(r); } public static double[][][] decomposeQR(double[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; double[][] q = new double[rows][cols]; double[][] r = new double[cols][cols]; // Initialize Q as an identity matrix for (int i = 0; i < rows; i++) { Arrays.fill(q[i], 0); q[i][i] = 1; } // Perform Householder transformations for (int k = 0; k < cols; k++) { double[] column = new double[rows - k]; // Construct the column vector for (int i = k; i < rows; i++) { column[i - k] = matrix[i][k]; } double norm = euclideanNorm(column); double[] u = new double[rows - k]; double[] v = new double[rows - k]; // Calculate u u[0] = column[0] + Math.signum(column[0]) * norm; for (int i = 1; i < u.length; i++) { u[i] = column[i]; } // Calculate v double uDotV = dotProduct(u, u); for (int i = 0; i < v.length; i++) { v[i] = u[i] / uDotV; } // Calculate Q double[][] qk = new double[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { qk[i][j] = q[i][j] - 2 * v[i] * dotProduct(v, q[i]); } } // Update Q for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { q[i][j] = qk[i][j]; } } // Calculate R for (int i = 0; i < cols; i++) { for (int j = i; j < cols; j++) { if (i == k) { r[i][j] = dotProduct(v, matrix[k]); } else { r[i][j] = r[i][j] + v[i] * dotProduct(v, matrix[j]); } } } } double[][][] qr = new double[2][][]; qr[0] = q; qr[1] = r; return qr; } public static double euclideanNorm(double[] vector) { double sum = 0; for (double v : vector) { sum += v * v; } return Math.sqrt(sum); } public static double dotProduct(double[] a, double[] b) { double sum = 0; for (int i = 0; i < a.length; i++) { sum += a[i] * b[i]; } return sum; } public static void printMatrix(double[][] matrix) { for (double[] row : matrix) { for (double value : row) { System.out.print(value + " "); } System.out.println(); } System.out.println(); } }
This program finds the QR decomposition of a given matrix using the Householder transformation method. The `decomposeQR()` method takes a matrix as input and returns a 3D array containing the matrices Q and R. The `printMatrix()` method is used to display the resulting matrices Q and R.
In this example, the input matrix is hard-coded as a 3×3 matrix. You can modify the program to accept a matrix of any size by adjusting the input matrix and the corresponding dimensions.
No comments yet! You be the first to comment.