Recursive Implementation

In this approach, we will implement a recursive function that calls itself again and again until it finds the determinant of the passed matrix. You can change the order of the matrix by changing the value of N, then pass a square matrix of the same order.

Example: The below code example implements recursion in JavaScript to find determinant of a matrix.

Javascript




// N is the Order of the matrix
let N = 3;
 
// Recursive function to find determinant
function determinantOfMatrixRecursive(mat, n) {
    if (n === 1) {
        return mat[0][0];
    }
    let det = 0;
    let sign = 1;
    for (let i = 0; i < n; i++) {
        let submatrix =
            createSubmatrix(mat, i, n);
        det += sign * mat[0][i] *
            determinantOfMatrixRecursive(submatrix, n - 1);
        sign = -sign;
    }
    return det;
}
 
// Function to find sub-matrices of different orders
function createSubmatrix(mat, colToRemove, n) {
    let submatrix = [];
    for (let i = 1; i < n; i++) {
        let newRow = [];
        for (let j = 0; j < n; j++) {
            if (j !== colToRemove) {
                newRow.push(mat[i][j]);
            }
        }
        submatrix.push(newRow);
    }
    return submatrix;
}
 
let mat = [
    [0, 4, -1],
    [0, 0, -2],
    [1, 2, -1]
];
console.log(
    "Determinant of the matrix is : ",
    determinantOfMatrixRecursive(mat, N)
);


Output

Determinant of the matrix is :  -8

Time complexity: O(n!)

Auxiliary Space: O(n^2), Space used for storing row.

JavaScript Program to Find the Determinant of a Matrix

The determinant is a term that is used to represent the matrices in terms of a real number. It can be defined only for the matrices that have the same number of rows and columns. Determinants can be used to find out the inverse of a matrix.

There are several ways to find the determinant of the matrix in JavaScript which are as follows:

Table of Content

  • Recursive Implementation
  • Non-Recursive Implementation

Similar Reads

Recursive Implementation

In this approach, we will implement a recursive function that calls itself again and again until it finds the determinant of the passed matrix. You can change the order of the matrix by changing the value of N, then pass a square matrix of the same order....

Non-Recursive Implementation

...

Contact Us