Java Program to Find Inverse of a Matrix

This is the java program to find the inverse of square invertible matrix. The matrix is invertible if its determinant is non zero.

Here is the source code of the Java Program to Find Inverse of a Matrix. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

//This is sample program to find the inverse of a matrix
 
import java.util.Scanner;
 
public class Inverse 
{
    public static void main(String argv[]) 
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the dimension of square matrix: ");
        int n = input.nextInt();
        double a[][]= new double[n][n];
        System.out.println("Enter the elements of matrix: ");
        for(int i=0; i<n; i++)
            for(int j=0; j<n; j++)
                a[i][j] = input.nextDouble();
 
        double d[][] = invert(a);
 
        System.out.println("The inverse is: ");
        for (int i=0; i<n; ++i) 
        {
            for (int j=0; j<n; ++j)
            {
                System.out.print(d[i][j]+"  ");
            }
            System.out.println();
        }
        input.close();
    }	
 
    public static double[][] invert(double a[][]) 
    {
        int n = a.length;
        double x[][] = new double[n][n];
        double b[][] = new double[n][n];
        int index[] = new int[n];
        for (int i=0; i<n; ++i) 
            b[i][i] = 1;
 
 // Transform the matrix into an upper triangle
        gaussian(a, index);
 
 // Update the matrix b[i][j] with the ratios stored
        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];
 
 // Perform backward substitutions
        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;
    }
 
// Method to carry out the partial-pivoting Gaussian
// elimination.  Here index[] stores pivoting order.
 
    public static void gaussian(double a[][], int index[]) 
    {
        int n = index.length;
        double c[] = new double[n];
 
 // Initialize the index
        for (int i=0; i<n; ++i) 
            index[i] = i;
 
 // Find the rescaling factors, one from each row
        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;
        }
 
 // Search the pivoting element from each column
        int k = 0;
        for (int j=0; j<n-1; ++j) 
        {
            double pi1 = 0;
            for (int i=j; i<n; ++i) 
            {
                double pi0 = Math.abs(a[index[i]][j]);
                pi0 /= c[index[i]];
                if (pi0 > pi1) 
                {
                    pi1 = pi0;
                    k = i;
                }
            }
 
   // Interchange rows according to the pivoting order
            int itmp = index[j];
            index[j] = index[k];
            index[k] = itmp;
            for (int i=j+1; i<n; ++i) 	
            {
                double pj = a[index[i]][j]/a[index[j]][j];
 
 // Record pivoting ratios below the diagonal
                a[index[i]][j] = pj;
 
 // Modify other elements accordingly
                for (int l=j+1; l<n; ++l)
                    a[index[i]][l] -= pj*a[index[j]][l];
            }
        }
    }
}

Output:

$ javac Inverse.java
$ java Inverse
Enter the dimension of square matrix: 
2
Enter the elements of matrix: 
1 2 
3 4 
The Inverse is: 
-1.9999999999999998  1.0  
1.4999999999999998  -0.49999999999999994

Related posts:

Java – Try with Resources
Java Program to Implement Adjacency Matrix
Hướng dẫn Java Design Pattern – Builder
Form Validation with AngularJS and Spring MVC
Java Program to Use Above Below Primitive to Test Whether Two Lines Intersect
Spring Boot Annotations
Spring Security Remember Me
Giới thiệu Java Service Provider Interface (SPI) – Tạo các ứng dụng Java dễ mở rộng
Request Method Not Supported (405) in Spring
HashSet trong Java hoạt động như thế nào?
JUnit5 Programmatic Extension Registration with @RegisterExtension
Getting Started with Stream Processing with Spring Cloud Data Flow
Convert Hex to ASCII in Java
How to Get All Dates Between Two Dates?
Documenting a Spring REST API Using OpenAPI 3.0
The Modulo Operator in Java
Performance Difference Between save() and saveAll() in Spring Data
Beans and Dependency Injection
Map Serialization and Deserialization with Jackson
Hướng dẫn Java Design Pattern – Prototype
Consuming RESTful Web Services
Java Program to Show the Duality Transformation of Line and Point
Finding Max/Min of a List or Collection
Marker Interface trong Java
Java 14 Record Keyword
Java Program to Perform Cryptography Using Transposition Technique
Convert String to Byte Array and Reverse in Java
Hướng dẫn Java Design Pattern – Chain of Responsibility
Java Program to Solve a Matching Problem for a Given Specific Case
Java Program to implement Circular Buffer
Java Program to Implement Euler Circuit Problem
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x