Multiply 2 matrices in Javascript

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

    Here's my ES6 soulution with math error handling:

    const matrixDot = (A, B) => {
      // Math error handling
      const matrices = [A, B];
      const cols = matrices.map((item) => item[0].length);
      if (!matrices.every((item, i) => item.every((row) => row.length === cols[i])))
        return console.error('All rows in a matrix must have equal amount of columns');
      else if (cols[0] !== B.length)
        return console.error(
          'Amount of columns in the 1st matrix must match amount of rows in the 2nd matrix'
        );
      // Calculations
      return A.map((rowA) =>
        B[0].map((_, colBIndex) =>
          rowA.reduce((acc, itemA, rowBIndex) => acc + itemA * B[rowBIndex][colBIndex], 0)
        )
      );
    };
    
    // Example
    const A = [
      [3, 2, 5],
      [6, 4, 1],
    ];
    const B = [
      [2, 6],
      [5, 3],
      [1, 4],
    ];
    console.log(matrixDot(A, B));
    // [ [21, 44],
    //   [33, 52] ]
    

    Here's gist if you want to bookmark it

    Hope it helps somebody ;)

提交回复
热议问题