Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,938 questions

51,875 answers

573 users

How to multiply two matrices (matrix) in Node.js

1 Answer

0 votes
const COLS_M1 = 3;
const COLS_M2 = 2;

const matrix1 = [
    [4, 2, 4], 
    [8, 3, 1]];
const matrix2 = [
    [3, 5], 
    [2, 8], 
    [7, 9]];

let mul = [
    [0, 0], 
    [0, 0]];

const rows1 = matrix1.length;
const cols2 = matrix2[0].length;

// mul[0][0] = m1[0][0] * m2[0][0] + m1[0][1] * m2[1][0] + m1[0][2] * m2[2][0]

for (let i = 0; i < rows1; i++) {
    for (let j = 0; j < cols2; j++) {
        for (let k = 0; k < COLS_M1; k++) {
            mul[i][j] += matrix1[i][k] * matrix2[k][j];
            
            console.log("mul["+ i +"]["+ j +"] += m1["+ i +"]["+ k +"] * m2["+ k +"]["+ j +"]");
        }
        console.log();
    }
}

for (let i = 0; i < COLS_M2; i++) {
    for (let j = 0; j < COLS_M2; j++) {
        console.log("mul[" + i + "][" + j + "] = " + mul[i][j]);
    }
}




/*
run:

mul[0][0] += m1[0][0] * m2[0][0]
mul[0][0] += m1[0][1] * m2[1][0]
mul[0][0] += m1[0][2] * m2[2][0]

mul[0][1] += m1[0][0] * m2[0][1]
mul[0][1] += m1[0][1] * m2[1][1]
mul[0][1] += m1[0][2] * m2[2][1]

mul[1][0] += m1[1][0] * m2[0][0]
mul[1][0] += m1[1][1] * m2[1][0]
mul[1][0] += m1[1][2] * m2[2][0]

mul[1][1] += m1[1][0] * m2[0][1]
mul[1][1] += m1[1][1] * m2[1][1]
mul[1][1] += m1[1][2] * m2[2][1]

mul[0][0] = 44
mul[0][1] = 72
mul[1][0] = 37
mul[1][1] = 73

*/

 



answered Sep 15, 2022 by avibootz

Related questions

1 answer 76 views
76 views asked Apr 29, 2024 by avibootz
1 answer 90 views
1 answer 89 views
1 answer 101 views
1 answer 130 views
1 answer 128 views
...