Write a JAVA program to read the values of an NxN matrix and print its inverse.

View Answers

December 20, 2010 at 3:51 PM

Hi Friend,

Try the following code:

import java.util.*; public class InverseMatrix { public static void main(String argv[]) { int matrix[][]= new int[3][3]; Scanner input=new Scanner(System.in); System.out.println("Enter elements of matrix: "); for (int i=0 ; i < matrix.length ; i++) for (int j=0 ; j < matrix[i].length ; j++){ matrix[i][j] = input.nextInt(); } int len = matrix.length; int inverseMatrix[][] = invert(matrix); System.out.println("Inverse of Matrix is: "); for (int i=0; i<len; ++i) { for (int j=0; j<len; ++j){ System.out.print(inverseMatrix[i][j]+" "); } System.out.println(); } } public static int[][] invert(int a[][]) { int n = a.length; int x[][] = new int[n][n]; int b[][] = new int[n][n]; int index[] = new int[n]; for (int i=0; i<n; ++i) b[i][i] = 1; findInverse(a, index); for (int i=0; i<n-1; ++i) for (int j=i+1; j<n; ++j) for (int k=0; k<n; ++k) b[index[j]][k] -= a[index[j]][i]*b[index[i]][k]; for (int i=0; i<n; ++i) { x[n-1][i] = b[index[n-1]][i]/a[index[n-1]][n-1]; for (int j=n-2; j>=0; --j) { x[j][i] = b[index[j]][i]; for (int k=j+1; k<n; ++k) { x[j][i] -= a[index[j]][k]*x[k][i]; } x[j][i] /= a[index[j]][j]; } } return x; } public static void findInverse(int a[][], int index[]) { int n = index.length; double c[] = new double[n]; for (int i=0; i<n; ++i) index[i] = i; for (int i=0; i<n; ++i) { double c1 = 0; for (int j=0; j<n; ++j) { double c0 = Math.abs(a[i][j]); if (c0 > c1) c1 = c0; } c[i] = c1; } int k = 0; for (int j=0; j<n-1; ++j) { double pi1 = 0; for (int i=j; i<n; ++i) { double p = Math.abs(a[index[i]][j]); p /= c[index[i]]; if (p > pi1) { pi1 = p; k = i; } } int temp = index[j]; index[j] = index[k]; index[k] = temp; for (int i=j+1; i<n; ++i) { int pj = a[index[i]][j]/a[index[j]][j]; a[index[i]][j] = pj; for (int l=j+1; l<n; ++l) a[index[i]][l] -= pj*a[index[j]][l]; } } } }

Thanks

Related Tutorials/Questions & Answers:

- Java Tutorials
- Java Code example
- Java Programming
- Java Beginners Examples
- Applet Tutorials
- Awt Tutorials
- Java Certification
- Interview Question
- Java Servlets Tutorial
- Jsp Tutorials
- Java Swing Tutorials
- JDBC Tutorial
- EJB Tutorials
- Java Server Faces (JSF) Tutorial
- WAP Tutorial
- Struts Tutorial
- JAXB Tutorial
- Spring FrameWork Tutorial
- SOA&Web Services Tutorials
- Bioinformatics Tutorials
- MySQL Tutorials
- JAVA DOM Tutorial
- XML Tutorial
- EAI Articles
- Many Programming Tutorials Links
- Tutorials Books
**Java Script Tutorial****Ajax Tutorial****Dojo Tutorials****Programming Books****Trainings****Flex****Ant****RDF**