Multiply 2 matrices in Javascript

后端 未结 9 2039
再見小時候
再見小時候 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 15:56

    This version stores rows as temporaries thus reducing the effective amount of index lookups. By this benchmark the achieved performance is almost 2 times faster if compared to the version withou storing rows.

    function multiply(a, b) {
        let aRows = a.length;
        let aCols = a[0].length;
        let bCols = b[0].length;
        let result = new Array(aRows); 
        for (let r = 0; r < aRows; ++r) {
            const row = new Array(bCols);
            result[r] = row;
            const ar = a[r];
            for (let c = 0; c < bCols; ++c) {
                let sum = 0.;     
                for (let i = 0; i < aCols; ++i) {
                    sum += ar[i] * b[i][c];
                }
                row[c] = sum;  
            }
        }
        return result;
    }
    
    const m = multiply(
            [[8, 3], [2, 4], [3, 6]],
            [[1, 2, 3], [4, 6, 8]]
        );
    console.log(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));

提交回复
热议问题