Non-Recursive Implementation

This method implements the JavaScript loops to iterate over the matrix elements and creates sub matrices to find the determinant of the matrix. You can change the value of N to change order of the matrix and pass a square matrix of same order.

Example: The below code example is a practical implementation of the iterative approach to find determinant of the matrix.

Javascript




// N is the order of the matrix
const N = 3;
 
function determinantOfMatrixIterative(mat, n) {
    let det = 1;
    let total = 1;
    const temp = Array(n).fill(0);
    for (let i = 0; i < n; i++) {
        let index = i;
        while (index < n && mat[index][i] === 0) {
            index++;
        }
        if (index === n) {
            continue;
        }
        if (index !== i) {
            for (let j = 0; j < n; j++) {
                [mat[i][j], mat[index][j]] =
                [mat[index][j], mat[i][j]];
            }
            det *= Math.pow(-1, index - i);
        }
        for (let j = 0; j < n; j++) {
            temp[j] = mat[i][j];
        }
        for (let j = i + 1; j < n; j++) {
            const num1 = temp[i];
            const num2 = mat[j][i];
            for (let k = 0; k < n; k++) {
                mat[j][k] =
                    num1 * mat[j][k] -
                    num2 * temp[k];
            }
            total *= num1;
        }
    }
    for (let i = 0; i < n; i++) {
        det *= mat[i][i];
    }
    return det / total;
}
 
const mat = [
    [8, 1, 2],
    [2, 1, 4],
    [1, 0, 5]
];
console.log(
    "Determinant of the matrix is:",
    determinantOfMatrixIterative(mat, N));


Output

Determinant of the matrix is: 32

Time Complexity: O(n^2)

Auxiliary Space: O(n)



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