How to multiply matrices in Node.js

1 Answer

0 votes
function Print(arr2d, size) {
    for (let i = 0; i < size; i++) {
        let s = "";
        for (let j = 0; j < size; j++)
            s +=  arr2d[i][j] + " ";
        console.log(s);
    }
    console.log();
}

function multiple_matrix(a, b, c, size) {
    for (let i = 0; i < size; i++) {
        for (let j = 0; j < size; j++) {
            c[i][j] = 0;
            for (let k = 0; k < size; k++) {
                c[i][j] = c[i][j] + a[i][k] * b[k][j];
            }
        }
    }
}     
 
const a = [ [ 1, 8, 5 ], 
            [ 6, 7, 1 ], 
            [ 8, 7, 6 ]];
const b = [ [ 2, 8, 1 ], 
            [ 6, 5, 3 ], 
            [ 4, 6, 5 ]];
const size = 3;

let c = new Array(size);
for (let i = 0; i < size; i++) {
    c[i] = new Array(size);
}

Print(a, size);
Print(b, size);

// c[0, 0] = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]) + (a[0, 2] * b[2, 0])
// c[0, 0] = 1 * 2 + 8 * 6 + 5 * 4 = 4 + 48 + 20 = 70
                        
multiple_matrix(a, b, c, size);
         
Print(c, size);


 
/*
run:
   
1 8 5 
6 7 1 
8 7 6 

2 8 1 
6 5 3 
4 6 5 

70 78 50 
58 89 32 
82 135 59 
     
*/

 



answered Apr 29, 2024 by avibootz

Related questions

...