Multiply 2 matrices in Javascript

后端 未结 9 2033
再見小時候
再見小時候 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:04

    For those interested in pure functional solution:

    let MatrixProd = (A, B) =>
      A.map((row, i) =>
        B[0].map((_, j) =>
          row.reduce((acc, _, n) =>
            acc + A[i][n] * B[n][j], 0
          )
        )
      )
    

    Testing code for your browser:

    let A = [[8, 3], [2, 4], [3, 6]];
    let B = [[1, 2, 3], [4, 6, 8]];
    console.table(MatrixProd(A,B));
    

提交回复
热议问题