Open In App

C++ Program For Determinant of a Matrix

Improve
Improve
Like Article
Like
Save
Share
Report

What is the Determinant of a Matrix? 
The determinant of a Matrix is a special number that is defined only for square matrices (matrices that have the same number of rows and columns). A determinant is used at many places in calculus and other matrices related to algebra, it actually represents the matrix in terms of a real number which can be used in solving a system of a linear equation and finding the inverse of a matrix.

How to calculate? 
The value of the determinant of a matrix can be calculated by the following procedure – 
For each element of the first row or first column get the cofactor of those elements and then multiply the element with the determinant of the corresponding cofactor, and finally add them with alternate signs. As a base case, the value of the determinant of a 1*1 matrix is the single value itself. 

Cofactor of an element is a matrix that we can get by removing the row and column of that element from that matrix.

Determinant of 2 x 2 Matrix:

A = egin{bmatrix} a & b\ c & d end{bmatrix} egin{vmatrix} A end{vmatrix}= ad - bc
 

22

Determinant of 3 x 3 Matrix: 
A = egin{bmatrix} a & b & c\ d & e & f\ g & h & i end{bmatrix} egin{vmatrix} A end{vmatrix}= a(ei-fh)-b(di-gf)+c(dh-eg)                             

C++

#include <iostream>
#include <cmath>
 
using namespace std;
 
const int MAXN = 105;
double a[MAXN][MAXN];
 
double determinant(int n) {
    double det = 1.0;
    for (int i = 0; i < n; i++) {
        int pivot = i;
        for (int j = i + 1; j < n; j++) {
            if (abs(a[j][i]) > abs(a[pivot][i])) {
                pivot = j;
            }
        }
        if (pivot != i) {
            swap(a[i], a[pivot]);
            det *= -1;
        }
        if (a[i][i] == 0) {
            return 0;
        }
        det *= a[i][i];
        for (int j = i + 1; j < n; j++) {
            double factor = a[j][i] / a[i][i];
            for (int k = i + 1; k < n; k++) {
                a[j][k] -= factor * a[i][k];
            }
        }
    }
    return det;
}
 
int main() {
    int n = 4;
    double matrix[4][4] = {{1, 0, 2, -1},
                           {3, 0, 0, 5},
                           {2, 1, 4, -3},
                           {1, 0, 5, 0}};
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            a[i][j] = matrix[i][j];
        }
    }
    double det = determinant(n);
    cout << "Determinant = " << det << endl;
    return 0;
}

                    

Output
Determinant of the matrix is : 30

Time Complexity: O(n!).

Explanation: The time complexity of the getCofactor() function is O(N^2) as it involves looping through all the elements of an N x N matrix. The time complexity of the determinantOfMatrix() function can be calculated using the following recurrence relation:

T(N) = N*T(N-1) + O(N^3)

The first term N*T(N-1) represents the time taken to calculate the determinant of the (N-1) x (N-1) submatrices, and the second term O(N^3) represents the time taken to calculate the cofactors for each element in the first row of the original matrix. Using expansion by minors, we can calculate the determinant of an NxN matrix as a sum of determinants of (N-1)x(N-1) matrices, each of which requires O(N^2) operations to calculate the cofactors. Therefore, the time complexity of the determinantOfMatrix() function is O(N!), which is the worst-case scenario where the matrix is a permutation matrix.

The display() function has a time complexity of O(N^2) as it loops through all the elements of the matrix to print them. The overall time complexity of the program is dominated by the determinantOfMatrix() function, so the time complexity of the program is O(N!).

Space Complexity: O(n*n) as temp matrix has been created.

Adjoint and Inverse of a Matrix 
There are various properties of the Determinant which can be helpful for solving problems related with matrices, 

In Above Method Recursive Approach is discussed. When the size of matrix is large it consumes more stack size 
In this Method We are using the properties of Determinant. In this approach we are converting the given matrix into upper triangular matrix using determinant properties The determinant of upper triangular matrix is the product of all diagonal elementsFor properties on determinant go through this website https://cran.r-project.org/web/packages/matlib/vignettes/det-ex1.html 

In this approach, we are iterating every diagonal element and making all the elements down the diagonal as zero using determinant properties 

If the diagonal element is zero then we will search next non zero element in the same column 

There exist two cases 
Case 1: 
If there is no non-zero element. In this case the determinant of matrix is zero 
Case 2: 
If there exists non-zero element there exist two cases 
Case a: 
if index is with respective diagonal row element. Using the determinant properties we make all the column elements down to it as zero 
Case b: 
Here we need to swap the row with respective to diagonal element column and continue the case ‘a; operation 

Below is the implementation of the above approach:

C++

#include<iostream>
#include<cmath>
using namespace std;
 
int determinant(int matrix[4][4], int n){
    int det = 0;
    int submatrix[4][4];
     
    if(n == 1){
        return matrix[0][0];
    }
    else if(n == 2){
        return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));
    }
    else{
        for(int x = 0; x < n; x++){
            int subi = 0;
            for(int i = 1; i < n; i++){
                int subj = 0;
                for(int j = 0; j < n; j++){
                    if(j == x){
                        continue;
                    }
                    submatrix[subi][subj] = matrix[i][j];
                    subj++;
                }
                subi++;
            }
            det = det + (pow(-1, x) * matrix[0][x] * determinant(submatrix, n-1));
        }
    }
    return det;
}
 
int main(){
    int matrix[4][4] = {{1, 0, 2, -1},
                     {3, 0, 0, 5},
                     {2, 1, 4, -3},
                     {1, 0, 5, 0}};
    int n = 4;
    int det = determinant(matrix, n);
    cout<<"Determinant: "<<det<<endl;
    return 0;
}

                    

Output
Determinant of the matrix is : 30

Time complexity: O(n3
Auxiliary Space: O(n) 

Approach: Gauss-Jordan Elimination

Steps:

  • Start with the given matrix and initialize the determinant to 1.
  • Apply elementary row operations to transform the matrix into its row echelon form, while keeping track of the determinant.
  • If any row interchange operations are performed, multiply the determinant by -1.
  • If any row has a leading coefficient of 0, the determinant is 0 and we can stop.
  • The determinant is the product of the diagonal entries in the row echelon form.
  • Return the determinant value.

C++

// C++ program for the above approach
#include <iostream>
using namespace std;
 
// Function to calculate the determinant
// of a matrix
int determinant(int** matrix, int size)
{
    int det = 0;
    int sign = 1;
 
    // Base Case
    if (size == 1) {
        det = matrix[0][0];
    }
    else if (size == 2) {
        det = (matrix[0][0] * matrix[1][1])
              - (matrix[0][1] * matrix[1][0]);
    }
 
    // Perform the Laplace Expansion
    else {
        for (int i = 0; i < size; i++) {
 
            // Stores the cofactor matrix
            int** cofactor = new int*[size - 1];
            for (int j = 0; j < size - 1; j++) {
                cofactor[j] = new int[size - 1];
            }
            int sub_i = 0, sub_j = 0;
            for (int j = 1; j < size; j++) {
                for (int k = 0; k < size; k++) {
                    if (k == i) {
                        continue;
                    }
                    cofactor[sub_i][sub_j] = matrix[j][k];
                    sub_j++;
                }
                sub_i++;
                sub_j = 0;
            }
 
            // Update the determinant value
            det += sign * matrix[0][i]
                   * determinant(cofactor, size - 1);
            sign = -sign;
            for (int j = 0; j < size - 1; j++) {
                delete[] cofactor[j];
            }
            delete[] cofactor;
        }
    }
 
    // Return the final determinant value
    return det;
}
 
// Driver Code
int main()
{
    int** matrix = new int*[4];
    for (int i = 0; i < 4; i++) {
        matrix[i] = new int[4];
    }
    matrix[0][0] = 1;
    matrix[0][1] = 0;
    matrix[0][2] = 2;
    matrix[0][3] = -1;
    matrix[1][0] = 3;
    matrix[1][1] = 0;
    matrix[1][2] = 0;
    matrix[1][3] = 5;
    matrix[2][0] = 2;
    matrix[2][1] = 1;
    matrix[2][2] = 4;
    matrix[2][3] = -3;
    matrix[3][0] = 1;
    matrix[3][1] = 0;
    matrix[3][2] = 5;
    matrix[3][3] = 0;
    int size = 4;
 
    int det = determinant(matrix, size);
 
    cout << "Determinant: " << det << endl;
 
    for (int i = 0; i < 4; i++) {
        delete[] matrix[i];
    }
    delete[] matrix;
 
    return 0;
}

                    

Output
Determinant = 30

Time Complexity: O(n^3) where n is the number of rows (or columns) in the matrix.

Auxiliary Space: O(1) as the matrix is modified in-place.

Approach Name: Cofactor Expansion

Steps:

  1. Define a function to calculate the determinant of a matrix using cofactor expansion.
  2. Check if the matrix is a square matrix, if not return an error message.
  3. If the matrix is 1×1, return the element.
  4. If the matrix is 2×2, return the determinant using the formula ad-bc.
  5. If the matrix is larger than 2×2, loop through the first row of the matrix and calculate the cofactor for each element.
  6. Multiply each cofactor by its corresponding element and the sign (+/-) of the element.
  7. Add the results of step 6 to get the determinant. 

C++


                    

Output
Determinant: 30

Time Complexity: O(n!)

Auxiliary Space: O(n^2)

Approach: Using the Laplace expansion method to calculate the determinant of a matrix.

Steps:

  1. Create a function that accepts a 2D array (matrix) and its size and perform the following steps:
    • Check if the matrix is square. If not, return an error message.
    • Check if the size of the matrix is 1. If yes, return the single value as the determinant.
    • Check if the size of the matrix is 2. If yes, calculate the determinant using the formula and return the value.
    • If the size of the matrix is greater than 2, implement the Laplace expansion method recursively.
      1. Choose a row or column to perform the expansion on.
      2. For each element in the chosen row/column, calculate its cofactor by removing the corresponding row and column.
      3. Multiply each cofactor by its corresponding element in the row/column and its sign (+/-).
      4. Add up all the results to obtain the determinant of the matrix.
    • Return the determinant value.

C++

// C++ program for the above approach
#include <iostream>
using namespace std;
 
// Function to calculate the determinant
// of a matrix
int determinant(int** matrix, int size)
{
    int det = 0;
    int sign = 1;
 
    // Base Case
    if (size == 1) {
        det = matrix[0][0];
    }
    else if (size == 2) {
        det = (matrix[0][0] * matrix[1][1])
              - (matrix[0][1] * matrix[1][0]);
    }
 
    // Perform the Laplace Expansion
    else {
        for (int i = 0; i < size; i++) {
 
            // Stores the cofactor matrix
            int** cofactor = new int*[size - 1];
            for (int j = 0; j < size - 1; j++) {
                cofactor[j] = new int[size - 1];
            }
            int sub_i = 0, sub_j = 0;
            for (int j = 1; j < size; j++) {
                for (int k = 0; k < size; k++) {
                    if (k == i) {
                        continue;
                    }
                    cofactor[sub_i][sub_j] = matrix[j][k];
                    sub_j++;
                }
                sub_i++;
                sub_j = 0;
            }
 
            // Update the determinant value
            det += sign * matrix[0][i]
                   * determinant(cofactor, size - 1);
            sign = -sign;
            for (int j = 0; j < size - 1; j++) {
                delete[] cofactor[j];
            }
            delete[] cofactor;
        }
    }
 
    // Return the final determinant value
    return det;
}
 
// Driver Code
int main()
{
    int** matrix = new int*[4];
    for (int i = 0; i < 4; i++) {
        matrix[i] = new int[4];
    }
    matrix[0][0] = 1;
    matrix[0][1] = 0;
    matrix[0][2] = 2;
    matrix[0][3] = -1;
    matrix[1][0] = 3;
    matrix[1][1] = 0;
    matrix[1][2] = 0;
    matrix[1][3] = 5;
    matrix[2][0] = 2;
    matrix[2][1] = 1;
    matrix[2][2] = 4;
    matrix[2][3] = -3;
    matrix[3][0] = 1;
    matrix[3][1] = 0;
    matrix[3][2] = 5;
    matrix[3][3] = 0;
    int size = 4;
 
    int det = determinant(matrix, size);
 
    cout << "Determinant: " << det << endl;
 
    for (int i = 0; i < 4; i++) {
        delete[] matrix[i];
    }
    delete[] matrix;
 
    return 0;
}

                    

Output
Determinant: 30

Time Complexity: O(N!)
Auxiliary Space: O(N!)



Last Updated : 07 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads