Multiply 2 matrices in Javascript

后端 未结 9 2034
再見小時候
再見小時候 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('&nbsp;&nbsp;'+m[r].join(' ')+'<br />');
        }
    }
    
    var a = [[8, 3], [2, 4], [3, 6]],
        b = [[1, 2, 3], [4, 6, 8]];
    document.write('matrix a:<br />');
    display(a);
    document.write('matrix b:<br />');
    display(b);
    document.write('a * b =<br />');
    display(multiply(a, b));

    0 讨论(0)
  • 2020-12-05 15:57

    npm install express

    node server.js

    var express = require('express');
    var app = express();
    
    
    var A=new Array(3);
    var B=new Array(3);
    var preA = [ 1, 2, 3, 4, 5, 6,7, 8, 9 ];
    var preB = [ 1,1 ,1,2,2, 2,3, 3, 3 ];
    
    //#########################preparing blank 3*3 matrix A and B###############
    for(i=0;i<3;i++){
        A[i]=new Array(3);
        B[i]=new Array(3);
    }
    
    
    
    //#####################Assigning values to matrix places from predefine arrays preA and preB #####
    var k=0;
    for(i=0;i<3;i++){
        for(j=0;j<3;j++){
    
            A[i][j]=preA[k];
            B[i][j]=preB[k];
            k++;
        }
    };
    
    
    console.log('################################');
    console.log('First matrix:');
    console.log(A[0]);
    console.log(A[1]);
    console.log(A[2]);
    console.log('');
    console.log('################################');
    console.log('Second matrix:');
    console.log(B[0]);
    console.log(B[1]);
    console.log(B[2]);
    
    //###################### multiplication logic as disscussed ################
    var result =[];
     for (var i = 0; i < 3; i++) {
            result[i] = new Array(3);
            for (var j = 0; j < 3; j++) {
                var sum = 0;
                for (var k = 0; k < 3; k++) {
                    sum += A[i][k] * B[k][j];
                }
                result[i][j] = sum;
            }
        }
    console.log('');
    console.log('################################');
    console.log('################################');
    console.log('After Multiplication');
    
    console.log(result[0]);
    console.log(result[1]);
    console.log(result[2]);
    
    
    
    app.listen(9999);
    
    0 讨论(0)
  • 2020-12-05 15:58

    I know it's an old question but I recommend to switch to my answer.

    My solution's got good performance because it uses Map Reduce functions

    //The chosen one
    function matrixDot (A, B) {
        var result = new Array(A.length).fill(0).map(row => new Array(B[0].length).fill(0));
    
        return result.map((row, i) => {
            return row.map((val, j) => {
                return A[i].reduce((sum, elm, k) => sum + (elm*B[k][j]) ,0)
            })
        })
    }
    
    var print = m => m.forEach(r => document.write(`&nbsp;&nbsp;${r.join(' ')}<br/>`)) 
    
    var a = [[8, 3], [2, 4], [3, 6]]
    var b = [[1, 2, 3], [4, 6, 8]]
    
    document.write('matrix a:<br />');
    print(a);
    document.write('matrix b:<br />');
    print(b);
    document.write('a * b =<br />');
    print(matrixDot(a,b));

    0 讨论(0)
  • 2020-12-05 15:59

    You can use multiplyMatrices() function from: http://tech.pro/tutorial/1527/matrix-multiplication-in-functional-javascript it works like charm. Example (You can print a matrix with style in Chrome and Firefox console with console.table() ):

    function multiplyMatrices(m1, m2) {
        var result = [];
        for (var i = 0; i < m1.length; i++) {
            result[i] = [];
            for (var j = 0; j < m2[0].length; j++) {
                var sum = 0;
                for (var k = 0; k < m1[0].length; k++) {
                    sum += m1[i][k] * m2[k][j];
                }
                result[i][j] = sum;
            }
        }
        return result;
    }
    
    var m1 = [[1,2],[3,4]]
    var m2 = [[5,6],[7,8]]
    
    var mResult = multiplyMatrices(m1, m2)
    
    /*In Google Chrome and Firefox you can do:*/
    
    console.table(mResult) /* it shows the matrix in a table */

    Result matrix in console.table()

    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 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('&nbsp;&nbsp;'+m[r].join(' ')+'<br />');
      }
    }
    
    var a = [[8, 3], [2, 4], [3, 6]],
        b = [[1, 2, 3], [4, 6, 8]];
    document.write('matrix a:<br />');
    display(a);
    document.write('matrix b:<br />');
    display(b);
    document.write('a * b =<br />');
    display(multiply(a, b));

    0 讨论(0)
提交回复
热议问题