Finding the pseudo-inverse of a matrix.
Here’s a Java program that finds the pseudo-inverse of a matrix:
import Jama.Matrix; public class PseudoInverse { public static void main(String[] args) { double[][] data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // Example matrix data Matrix matrix = new Matrix(data); Matrix pseudoInverse = getPseudoInverse(matrix); // Print the pseudo-inverse matrix System.out.println("Pseudo-inverse of the matrix:"); printMatrix(pseudoInverse); } public static Matrix getPseudoInverse(Matrix matrix) { int m = matrix.getRowDimension(); int n = matrix.getColumnDimension(); // Perform Singular Value Decomposition (SVD) Jama.SingularValueDecomposition svd = matrix.svd(); // Get the singular values double[] singularValues = svd.getSingularValues(); // Set a tolerance threshold to determine non-zero singular values double tolerance = Math.max(m, n) * singularValues[0] * 1e-15; // Invert the non-zero singular values for (int i = 0; i < singularValues.length; i++) { if (Math.abs(singularValues[i]) > tolerance) { singularValues[i] = 1.0 / singularValues[i]; } else { singularValues[i] = 0.0; } } // Construct the pseudo-inverse matrix Matrix singularValueMatrix = Matrix.diag(singularValues); Matrix v = svd.getV(); Matrix u = svd.getU(); Matrix pseudoInverse = v.times(singularValueMatrix.transpose()).times(u.transpose()); return pseudoInverse; } public static void printMatrix(Matrix matrix) { int rows = matrix.getRowDimension(); int cols = matrix.getColumnDimension(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { System.out.print(matrix.get(i, j) + " "); } System.out.println(); } } }
This program uses the `Jama` library, which provides functionality for performing matrix operations. The `getPseudoInverse` method takes a matrix as input, performs Singular Value Decomposition (SVD), and constructs the pseudo-inverse matrix based on the singular values. The `printMatrix` method is used to display the resulting pseudo-inverse matrix. In the example, the matrix `{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}` is used, but you can modify it with your desired matrix data.
No comments yet! You be the first to comment.