The Wayback Machine - https://web.archive.org/web/20240909163815/https://www.geeksforgeeks.org/java-program-to-find-the-determinant-of-a-matrix/
Open In App

Java Program to Find the Determinant of a Matrix

Last Updated : 06 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Determinant of a Matrix is a real number that can be defined for square matrices only i.e, the number of rows and columns of the matrices must be equal. Moreover, it is helpful in determining the system of the linear equation as well as figuring the inverse of the stated matrix.

Procedure to calculate:

  • First, we need to calculate the cofactor of all the elements of the matrix in the first row or first column.
  • Then, multiply each element of the first row or first column with their respective cofactor.
  • At last, we need to add them up with alternate signs.

Example:

  • Determinant of 2*2 matrix:
[4, 3]
[2, 3]

= (4*3)-(3*2)
= 12-6
= 6
  • Determinant of 3*3 matrix:
[1, 3, -2]
[-1, 2, 1]
[1, 0, -2]

= 1(-4-0)-3(2-1)+(-2)(0-2)
= -4-3+4
= -3

Note:

  1. The determinant of 1*1 matrix is the element itself.
  2. The Cofactor of any element of the stated matrix can be calculated by eliminating the row and the column of that element from the matrix stated.

Let’s see an example in order to get a clear concept of the above topic.

Example: Using Recursion

Java




// Java program to find
// Determinant of a matrix
class GFG {
 
    // Dimension of input square matrix
    static final int N = 2;
 
    // Function to get cofactor of
    // mat[p][q] in temp[][]. n is
    // current dimension of mat[][]
    static void getCofactor(int mat[][], int temp[][],
                            int p, int q, int n)
    {
        int i = 0, j = 0;
 
        // Looping for each element
        // of the matrix
        for (int row = 0; row < n; row++) {
            for (int col = 0; col < n; col++) {
                // Copying into temporary matrix
                // only those element which are
                // not in given row and column
                if (row != p && col != q) {
                    temp[i][j++] = mat[row][col];
                    // Row is filled, so increase
                    // row index and reset col index
                    if (j == n - 1) {
                        j = 0;
                        i++;
                    }
                }
            }
        }
    }
 
    /* Recursive function for finding determinant
    of matrix. n is current dimension of mat[][]. */
    static int determinantOfMatrix(int mat[][], int n)
    {
        int D = 0; // Initialize result
 
        // Base case : if matrix
        // contains single element
        if (n == 1)
            return mat[0][0];
 
        // To store cofactors
        int temp[][] = new int[N][N];
 
        // To store sign multiplier
        int sign = 1;
 
        // Iterate for each element of first row
        for (int f = 0; f < n; f++) {
            // Getting Cofactor of mat[0][f]
            getCofactor(mat, temp, 0, f, n);
            D += sign * mat[0][f]
                 * determinantOfMatrix(temp, n - 1);
 
            // terms are to be added
            // with alternate sign
            sign = -sign;
        }
 
        return D;
    }
 
    /* function for displaying the matrix */
    static void display(int mat[][], int row, int col)
    {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++)
                System.out.print(mat[i][j]);
 
            System.out.print("\n");
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        int mat[][] = { { 4, 3 }, { 2, 3 } };
 
        System.out.print("Determinant "
                         + "of the matrix is : "
                         + determinantOfMatrix(mat, N));
    }
}


Output

Determinant of the matrix is : 6

Time complexity: O(n3) 

Example: Non-recursion Implementation 

Java




// Java program to find Determinant of a matrix
class GFG {
 
    // Dimension of input square matrix
    static final int N = 4;
 
    // Function to get determinant of matrix
    static int determinantOfMatrix(int mat[][], int n)
    {
        int num1, num2, det = 1, index,
                        total = 1; // Initialize result
 
        // temporary array for storing row
        int[] temp = new int[n + 1];
 
        // loop for traversing the diagonal elements
        for (int i = 0; i < n; i++) {
            index = i; // initialize the index
 
            // finding the index which has non zero value
            while (mat[index][i] == 0 && index < n) {
                index++;
            }
            if (index == n) // if there is non zero element
            {
                // the determinant of matrix as zero
                continue;
            }
            if (index != i) {
                // loop for swapping the diagonal element row
                // and index row
                for (int j = 0; j < n; j++) {
                    swap(mat, index, j, i, j);
                }
                // determinant sign changes when we shift
                // rows go through determinant properties
                det = (int)(det * Math.pow(-1, index - i));
            }
 
            // storing the values of diagonal row elements
            for (int j = 0; j < n; j++) {
                temp[j] = mat[i][j];
            }
 
            // traversing every row below the diagonal
            // element
            for (int j = i + 1; j < n; j++) {
                num1 = temp[i]; // value of diagonal element
                num2 = mat[j]
                          [i]; // value of next row element
 
                // traversing every column of row
                // and multiplying to every row
                for (int k = 0; k < n; k++) {
                    // multiplying to make the diagonal
                    // element and next row element equal
                    mat[j][k] = (num1 * mat[j][k])
                                - (num2 * temp[k]);
                }
                total = total * num1; // Det(kA)=kDet(A);
            }
        }
 
        // multiplying the diagonal elements to get
        // determinant
        for (int i = 0; i < n; i++) {
            det = det * mat[i][i];
        }
        return (det / total); // Det(kA)/k=Det(A);
    }
 
    static int[][] swap(int[][] arr, int i1, int j1, int i2,
                        int j2)
    {
        int temp = arr[i1][j1];
        arr[i1][j1] = arr[i2][j2];
        arr[i2][j2] = temp;
        return arr;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int mat[][] = { { 1, 0, 2, -1 },
                        { 3, 0, 0, 5 },
                        { 2, 1, 4, -3 },
                        { 1, 0, 5, 0 } };
 
        // Function call
        System.out.printf(
            "Determinant of the matrix is : %d",
            determinantOfMatrix(mat, N));
    }
}


Output

Determinant of the matrix is : 30

Time complexity: O(n3) 

 



Previous Article
Next Article

Similar Reads

Java Program to Determine if a given Matrix is a Sparse Matrix
A matrix is a collection of data elements arranged in a two-dimensional array-like structure, consisting of rows and columns. A matrix with a lot of zero values is called a sparse matrix. The program aims to count the number of zero values present in the matrix. If the number of zero values is more than half of the total number of elements in the m
3 min read
Java Program to Check Whether a Given Matrix is Lower Triangular Matrix or Not
In the lower triangular matrix, the elements that are present above the diagonal should be 0. Given a matrix and the task is to check the matrix is in lower triangular form or not. A matrix must be a square matrix. A square matrix is called lower triangular if all the entries above the main diagonal are zero. Example - Input: 1 0 0 1 2 0 1 2 3 Outp
2 min read
Java Program to Find the Frequency of Odd &amp; Even Numbers in the Matrix
Matrix is simply a two-dimensional array. Just like in one-dimensional traversal operation is required to figure out. The task is to find the frequencies of odd and even number in the given matrix. The size of matrix is defined as product of numbers of columns and rows. So, the size of the matrix is m × n Here in the matrix M = number of rows in th
3 min read
Java Program to Find Transpose of Matrix
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, the transpose of A[][] is obtained by changing A[i][j] to A[j][i]. Find Transpose of a Matrix in Java There are two shapes in Matrix to find transpose as mentioned below: Square MatrixRectangle Matrix1. Transpose of Square Matrix The below program fin
4 min read
Java Program to Find Laplacian Matrix of an Undirected Graph
The Laplacian matrix, also called the graph Laplacian, admittance matrix, Kirchhoff matrix or discrete Laplacian, is a matrix representation of a graph. To find the Laplacian matrix first, find adjacency matrix and degree matrix of a graph as the formula for the Laplacian matrix is as follows: Laplacian matrix = Degree matrix - Adjacency matrix Exa
4 min read
Java Program to Find the Normal and Trace of a Matrix
For a given 2D matrix, the purpose is to find the Trace and Normal of the matrix. Normal of a matrix is defined as the square root of the sum of squares of all the elements of the matrix. Trace of a given square matrix is defined as the sum of all the elements in the diagonal. Examples : Input : matrix[][] = {{1, 4, 4}, {2, 3, 7}, {0, 5, 1}}; Outpu
2 min read
Java Program to Find the Maximum Element in a Matrix
Given a multi-dimensional 2D matrix of n rows and m column order N × M. The task is to find the maximum element in the given matrix. Illustration: Input : mat[][] = { {1,3,4,19}, {11,10,12,1}, {7,9,0,4,99} } Output : 99 Methods: Iterative method (naive approach)Using the principle of recursion (Bit more optimal approach) Method 1: Iterative method
3 min read
Java Program to Find maximum element of each row in a matrix
Given a matrix, the task is to find the maximum element of each row. Examples: Input : [1, 2, 3] [1, 4, 9] [76, 34, 21] Output : 3 9 76 Input : [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2] Output : 21 65 56 Approach : Approach is very simple. The idea is to run the loop for no_of_rows. Check each element inside the row and find for the maximum eleme
2 min read
Java Program to Find median in row wise sorted matrix
We are given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.Examples:  Input : 1 3 5 2 6 9 3 6 9 Output : Median is 5 If we put all the values in a sorted array A[] = 1 2 3 3 5 6 6 9 9) Input: 1 3 4 2 5 6 7 8 9 Output: Median is 5Recommended: Please solve it on “PRACTICE ”
4 min read
Java Program for Program to find area of a circle
Area of a circle can simply be evaluated using following formula. Area = pi * r2 where r is radius of circle Java Code // Java program to find area // of circle class Test { static final double PI = Math.PI; static double findArea(int r) { return PI * Math.pow(r, 2); } // Driver method public static void main(String[] args) { System.out.println(
1 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java Program to Print Matrix in Z form
Given a square matrix of order n*n, we need to print elements of the matrix in Z form Examples: Input : mat[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : 1 2 3 5 7 8 9 Input : mat[][] = {5, 19, 8, 7, 4, 1, 14, 8, 2, 20, 1, 9, 1, 2, 55, 4} Output: 5 19 8 7 14 20 1 2 55 4 Java Code // Java program to print a // square matrix in Z form import java.lang.*
2 min read
Java Program to Interchange Any Two Rows in the Matrix
Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Rows in the given matrix. Swap Operation is required to interchange the elements of two rows. O(1) operation to swap two rows is impossible because complete traversal between two rows is required. Examples Input 1: K = 1, L = 2, mat[][] = {{2, 1, 4},
2 min read
Java Program for Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
3 min read
Java Program to Interchange Elements of First and Last in a Matrix Across Columns
For a given 4 x 4 matrix, the task is to interchange the elements of the first and last columns and then return the resultant matrix. Examples : Input 1 : 1 1 5 0 2 3 7 2 8 9 1 3 6 7 8 2 Output 1 : 0 1 5 1 2 3 7 2 3 9 1 8 2 7 8 6 Input 2 : 7 8 9 10 11 13 14 1 15 7 12 22 11 21 30 1 Output 2 : 10 8 9 7 1 13 14 11 22 7 12 15 1 21 30 11 Approach: To ge
3 min read
Java Program to Add Two Matrix Using Iterative Approach
Given two matrices A and B, Add two matrices using iterative approaches in Java, like for loop, while loop, do-while loop. For the addition of two matrices, the necessary condition is that both the matrices must have the same size, and addition must take complete iteration to both the matrices. Examples Input: A[][] = {{1, 3}, {2, 4}} B[][] = {{1,
2 min read
Java Program to Display Upper Triangular Matrix
Upper Triangular Matrix is a matrix in which all the elements below the principal matrix are 0. A necessary condition is that matrix must be Square matrix in nature. If the matrix is not a square matrix, it can never be called the upper triangular matrix. ExamplesInput 1: mat[][] = { {2, 1, 4}, {1, 2, 3}, {3, 6, 2} } Output : mat[][]= { {2, 1, 4},
2 min read
Java Program to Display Lower Triangular Matrix
Lower Triangular Matrix is a square matrix in which all the elements above the principal diagonal are 0. If the matrix is not a square matrix, it can never be called the lower triangular matrix. Examples Input 1: mat[][] = { {2, 1, 4}, {1, 2, 3}, {3, 6, 2}} Output : mat[][]= {{2, 0, 0}, {1, 2, 0}, {3, 6, 2}} Explanation : All the element below the
2 min read
Java Program to Interchange Any Two Columns in the Matrix
Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Columns(ie column no K and L given in the input) in the given matrix. Swap Operation is required to interchange the elements of two columns. O(1) operation to swap two columns is impossible because complete traversal between two columns is required. E
2 min read
Java Program to Accept a Matrix of Order M x N & Interchange the Diagonals
Problem Description: Write a Java program that accepts a matrix of M × N order and then interchange diagonals of the matrix. Steps: 1. We can only interchange diagonals for a square matrix. 2. Create a square matrix of size [M × M]. 3. Check the matrix is a square matrix or not. If the matrix is square then follow step 3 else terminate the program.
4 min read
Java Program to Represent Linear Equations in Matrix Form
Let's look at the System of Linear Equation with the help of an example: The input of coefficients and variables is taken into play for consideration. The scanner package should be imported into the program in order to use the object of the Scanner class to take the input from the user.The array will be initialized to store the variables of the equ
4 min read
Java Program to Check Whether a Matrix is Symmetric or Not
A symmetric matrix is a square matrix in which the transpose of the square matrix is the same as the original square matrix. A square matrix is a matrix in which the number of columns is the same as the number of rows. If the matrix is a symmetric matrix then it is also a square matrix but vice versa isn't true. Matrix is simply considered as 2D ar
4 min read
Java Program to Create a Matrix and Fill it with Prime Numbers
Prime Numbers are the number which can be divisible by only 1 and itself, it cannot be divisible by any other number. The task here is to find the prime numbers and store them in the form of a matrix. Example: Prime numbers are: 2, 3, 5, 7 Output: 2 3 5 7 Prime numbers : 2, 3, 5, 7, 9, 11, 13, 17, 19 Output: 2 3 5 7 9 11 13 17 19 Approach: First, t
3 min read
Java Program to Display Transpose Matrix
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]. Approach: Create a 2-D Array.Insert the values in the array by running two nested loops. The outer ith loop will go till the no.of rows and the inner jth loop will run till the number of c
2 min read
Java Program to Print Boundary Elements of the Matrix
Given a matrix of size Row x Col Print the boundary elements of the matrix. Boundary elements are those elements which are not surrounded by elements on all four directions, i.e. elements in the first row, first column, last row and last column. Example: Input : 1 2 3 4 5 6 7 8 9 Output: 1 2 3 4 6 7 8 9Approach: Take the matrix as input from the us
2 min read
Java Program to Interchange Elements of First and Last in a Matrix Across Rows
For a given 4 × 4 matrix, the task is to interchange the elements of the first and last rows and then return the resultant matrix. Illustration: Input 1: 1 1 5 0 2 3 7 2 8 9 1 3 6 7 8 2 Output 1: 6 7 8 2 2 3 7 2 8 9 1 3 1 1 5 0 Input 2: 7 8 9 10 11 13 14 1 15 7 12 22 11 21 30 1 Output 2: 11 21 30 1 11 13 14 1 15 7 12 22 7 8 9 10 Approach: To get th
3 min read
Java Program to Rotate Matrix Elements
Matrix is simply a two-dimensional array. So the goal is to deal with fixed indices at which elements are present and to perform operations on indexes such that elements on the addressed should be swapped in such a manner it should lookout as the matrix is rotated. Here we will be discussing two methods in dealing with indices Using naive approach
6 min read
Java Program to Compute the Sum of Diagonals of a Matrix
For a given 2D square matrix of size N*N, the task is to find the sum of elements in the Principal and Secondary diagonals. For example, analyze the following 4 × 4 input matrix. a00 a01 a02 a03a10 a11 a12 a13a20 a21 a22 a23a30 a31 a32 a33 Example: Input 1 : 6 7 3 4 8 9 2 1 1 2 9 6 6 5 7 2Output 1 : Principal Diagonal: 26 Secondary Diagonal: 14 Inp
4 min read
Java Program to Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction
Given a square matrix mat[][] of dimension N and an integer K, the task is to rotate the matrix by 90 degrees K times without changing the position of the diagonal elements. Examples: Input: mat[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}, K = 1Output: 1 16 11 6 5 22 7 12 9 2 23 18 13
4 min read
Java Program to Modify a matrix by rotating ith row exactly i times in clockwise direction
Given a matrix mat[][] of dimensions M * N, the task is to print the matrix obtained after rotating every ith row of the matrix i times in a clockwise direction. Examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output:1 2 36 4 58 9 7Explanation:The 0th row is rotated 0 times. Therefore, the 0th row remains the same as {1, 2, 3}.The 1st r
3 min read
Article Tags :
Practice Tags :