How to calculate the determinant of a matrix in javascript?

11

Eg: det([-1, -2, 3], [3, 3, 1], [-1, 2, -3]) // retorna 22

Eg: det([1, 2], [2, 5]) // retorna 1

Eg: det([8]) // retorna 8

    
asked by anonymous 10.02.2014 / 21:12

2 answers

12

I created the following function in 2010, but I made some improvements recently:

function determinante(a) {
    var ordem = a.length;

    if (ordem === 1) {
        return a[0][0];
    }

    if (ordem === 2) {
        return a[0][0] * a[1][1] - a[0][1] * a[1][0];
    }

    var det = 0;

    for (var j = 0; j < ordem; j++) {
        det += a[0][j] * cofator(a, 0, j);
    }

    return det;
}

function cofator(a, linha, coluna) {
    var sub_matriz = [],
        ordem = a.length,
        m = 0;

    for (var i = 1; i < ordem; i++) {
        sub_matriz[m] = [];

        for (var j = 0; j < ordem; j++) {
            if (j !== coluna) {
                sub_matriz[m].push(a[i][j]);
            }
        }
        m++;
    }

    //return Math.pow(-1, linha + coluna) * determinante(sub_matriz);
    return (coluna % 2 ? -1 : 1) * determinante(sub_matriz);
}



The determinante function is indirect recursive (The flame B, B calls A) and uses the Theorem of Laplace to calculate the determinant of a square matrix. The theorem is always applied to the first row of the matrix, not to the row or column with the largest number of zeros, as we do on paper.

Examples of use:

determinante([[1,-2,8,4,-3,1], [-2,-9,3,1,4,-4], [3,0,8,7,0,2], [5,7,1,2,5,-1], [7,-8,-6,4,0,-5], [0,-2,-8,0,0,1]])
// Retorna 1560

Check out: link

determinante([[1,2,3], [4,5,6], [7,8,1]]);
// Retorna 24

Check out: #

determinante([[-1,-2,3], [3,3,1], [-1,2,-3]]);
// Retorna 22

Check out: link

determinante([[8]]);
// Retorna 8
determinante([
    [2, 1, 2, 3, 4, 5, 6, 7, 2, 3],
    [0, 2, 0, 0, 0, 0, 0, 2, 3, 2],
    [0, 0, 4, 5, 5, 5, 2, 3, 2, 1],
    [0, 0, 0, 2, 0, 2, 3, 2, 5, 2],
    [0, 0, 0, 0, 4, 3, 2, 0, 5, 3],
    [0, 0, 0, 0, 0, 1, 0, 0, 5, 4],
    [0, 0, 0, 0, 0, 0, 4, 0, 5, 5],
    [0, 0, 0, 0, 0, 0, 0, 2, 5, 6],
    [0, 0, 0, 0, 0, 0, 0, 0, 1, 7],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 2]
]);
// Retorna 2048

FIDDLE: link

Note: In fact, the implementation using the Laplace Theorem is not the most efficient, but it is easy to visualize and works well for relatively small matrices (order

10.02.2014 / 21:18
4

The direct calculation of the determinant by the cofactors is didactic but quite inefficient if you want to use large matrices seriously.

A better option would be to calculate the LU decomposition. Since the matrices L and U are triangular, the determinant of each is simply the multiplication of the elements of the principal diagonal. If A = LU then | A | = | L || U |.

The best would be to use the Sylvester.js library link

    
10.02.2014 / 21:32