Finding the matrix eigenvalues using Householder transformation
Here’s a Java code snippet that demonstrates how to find the eigenvalues of a matrix using Householder transformation:
import java.util.Arrays; public class HouseholderEigenvalues { // Helper function to print a matrix private static void printMatrix(double[][] matrix) { for (double[] row : matrix) { System.out.println(Arrays.toString(row)); } System.out.println(); } // Helper function to compute the dot product of two vectors private static double dotProduct(double[] vector1, double[] vector2) { double result = 0.0; for (int i = 0; i < vector1.length; i++) { result += vector1[i] * vector2[i]; } return result; } // Helper function to apply Householder transformation to a matrix private static void applyHouseholderTransformation(double[][] matrix, double[] v) { int n = matrix.length; double[] w = new double[n]; for (int j = 0; j < n; j++) { double dot = 0.0; for (int i = 0; i < n; i++) { dot += matrix[i][j] * v[i]; } for (int i = 0; i < n; i++) { w[i] += dot * v[i]; } } for (int j = 0; j < n; j++) { for (int i = 0; i < n; i++) { matrix[i][j] -= 2.0 * v[i] * w[j]; } } } // Function to compute the eigenvalues of a matrix using Householder transformation public static double[] findEigenvalues(double[][] matrix) { int n = matrix.length; double[] eigenvalues = new double[n]; for (int k = n - 1; k >= 1; k--) { double[] v = new double[n]; for (int i = 0; i < k; i++) { v[i] = matrix[i][k]; } v[k] = 1.0; applyHouseholderTransformation(matrix, v); double sum = 0.0; for (int i = 0; i < k; i++) { sum += matrix[i][k] * matrix[i][k]; } double norm = Math.sqrt(sum); double alpha = -Math.signum(matrix[k][k]) * norm; for (int i = 0; i < k; i++) { matrix[i][k] /= alpha; } matrix[k][k] -= 1.0; for (int j = 0; j < k; j++) { matrix[k][j] = 0.0; } } for (int i = 0; i < n; i++) { eigenvalues[i] = matrix[i][i]; } return eigenvalues; } public static void main(String[] args) { double[][] matrix = { {1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0} }; System.out.println("Original Matrix:"); printMatrix(matrix); double[] eigenvalues = findEigenvalues(matrix); System.out.println("Eigenvalues:"); System.out.println(Arrays.toString(eigen values)); } }
In this code, the `findEigenvalues` method implements the Householder transformation algorithm to compute the eigenvalues of a given matrix. The `applyHouseholderTransformation` method applies the Householder transformation to the matrix. The `dotProduct` method computes the dot product of two vectors. The `printMatrix` method is a helper function to print the matrix.
In the `main` method, a sample matrix is defined and its eigenvalues are computed using the `findEigenvalues` method. The resulting eigenvalues are then printed to the console.
Note: This code assumes that the input matrix is square.
No comments yet! You be the first to comment.