Multiply 2 matrices in Javascript

后端 未结 9 2050
再見小時候
再見小時候 2020-12-05 15:31

I\'m doing a function that multiplies 2 matrices. The matrices will always have the same number of rows and columns. (2x2, 5x5, 23x23, ...)

When I print it, it doesn

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 16:08

    You're getting confused with your various temporary arrays. The undefined values are caused by out-of-bounds access on the line below your innermost loop.

    I recommend that you stick to making a single array for the result of the multiplication. As you're probably aware, the hitch is that JavaScript doesn't allow you to initialize a multi-dimensional array. To make a two-dimensional array, you have to initialize a one-dimensional array, then iterate over its elements and initialize each one to a one-dimensional array.

    function multiply(a, b) {
      var aNumRows = a.length, aNumCols = a[0].length,
          bNumRows = b.length, bNumCols = b[0].length,
          m = new Array(aNumRows);  // initialize array of rows
      for (var r = 0; r < aNumRows; ++r) {
        m[r] = new Array(bNumCols); // initialize the current row
        for (var c = 0; c < bNumCols; ++c) {
          m[r][c] = 0;             // initialize the current cell
          for (var i = 0; i < aNumCols; ++i) {
            m[r][c] += a[r][i] * b[i][c];
          }
        }
      }
      return m;
    }
    
    function display(m) {
      for (var r = 0; r < m.length; ++r) {
        document.write('  '+m[r].join(' ')+'
    '); } } var a = [[8, 3], [2, 4], [3, 6]], b = [[1, 2, 3], [4, 6, 8]]; document.write('matrix a:
    '); display(a); document.write('matrix b:
    '); display(b); document.write('a * b =
    '); display(multiply(a, b));

提交回复
热议问题