2

I'm trying to compute determinant of a matrix in JS. I used algorithm from http://www.sanfoundry.com/java-program-compute-determinant-matrix/ but I lost my mind on the last condition. I just do not understand. Can you help me?

This is how looks like my code right now. In another function I create an empty 2d array and then copy it to det function. Next I retrieve values from html and then trying to compute determinant of a matrix. The first 2 cases are simple but I have a problem with the last one. I couldn't find working example in JS.

function det() {
  var det = 0;
  var array1 = array.slice();

  for (i = 0; i < array1.length; i++) {

    for (j = 0; j < array1[i].length; j++) {
      array1[i][j] = parseInt(document.getElementById("element" + (i + 1) + (j + 1)).value, 10);
    }

  }

  if (array1.length == 1) {
    det = array1[0][0];
  } else if (array1.length == 2) {
    det = (array1[0][0] * array1[1][1]) - (array1[1][0] * array1[0][1]);
  } else {

  }

}
sa77
  • 3,485
  • 3
  • 20
  • 35
kureva
  • 55
  • 1
  • 7
  • in the last condition , you create a sub matrix which is `array1` deleting the row and column at `a0j` where `j` is from `0` to `N`, you multiply `a0j` with `det(subarray)` and the sum of the products is the final `determinant` , that is the definition of `determinant`, the code written before the recursive call is just filling the subarray that's all – niceman Jun 10 '17 at 15:33
  • Recursion is nice, but be warned with js https://stackoverflow.com/questions/37224520/are-functions-in-javascript-tail-call-optimized – Richard Tyler Miles Nov 23 '21 at 05:24

2 Answers2

10

I may suggest my solution, based on recursive algorithm, which takes only few lines of code and, I guess, will suit most of practical applications:

const determinant = m => 
  m.length == 1 ?
  m[0][0] :
  m.length == 2 ? 
  m[0][0]*m[1][1]-m[0][1]*m[1][0] :
  m[0].reduce((r,e,i) => 
    r+(-1)**(i+2)*e*determinant(m.slice(1).map(c => 
      c.filter((_,j) => i != j))),0)

const test1 = [[3]]                      // 3
const test2 = [[3,-2],[7,4]]             // 26
const test3 = [[1,3,7],[2,-1,4],[5,0,2]] // 81

console.log(determinant(test1))
console.log(determinant(test2))
console.log(determinant(test3))
.as-console-wrapper {min-height: 100%}
Yevgen Gorbunkov
  • 14,071
  • 3
  • 15
  • 36
0

You can see definition of the determinant for square matrix here https://en.wikipedia.org/wiki/Determinant#n_.C3.97_n_matrices. Algorithm used in http://www.sanfoundry.com/java-program-compute-determinant-matrix/ use some properties of determinat to calculate it in recursive way as sum over all permutations. In this way you get N * N! operations! It is very big even for small N.

For solving this problem you can first transform matrix to triangular with the same determinant and after that calculate determinant as product of all diagonal elements.

ivan kuklin
  • 140
  • 2
  • 8