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

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,038 questions

40,794 answers

573 users

How to multiply two matrices (matrix) in C++

1 Answer

0 votes
#include <iostream>

#define COLS1 3
#define COLS2 2

int main()
{
    int matrix1[][COLS1] = { {4, 2, 4},
                             {8, 3, 1} };
    int matrix2[][COLS2] = { {3, 5},
                             {2, 8},
                             {7, 9} };
    int mul[][COLS2] =     { {0, 0},
                             {0, 0} };

    int rows1 = sizeof(matrix1) / sizeof(matrix1[0]);
    int cols2 = sizeof(matrix2[0]) / sizeof(matrix2[0][0]);

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

    for (int i = 0; i < rows1; i++) {
        for (int j = 0; j < cols2; j++) {
            for (int k = 0; k < COLS1; k++) {
                mul[i][j] += matrix1[i][k] * matrix2[k][j];
                std::cout << "mul["<< i <<"]["<< j <<"] += m1["<< i <<"]["<< k <<"] * m2["<< k <<"]["<< j <<"]\n";
            }
            std::cout << "\n";
        }
    }

    for (int i = 0; i < COLS2; i++) {
        for (int j = 0; j < COLS2; j++)
            std::cout << mul[i][j] << " ";
        std::cout << "\n";
    }
}



/*
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]

44 72 
37 73 

*/

 





answered May 7, 2021 by avibootz
edited Oct 2, 2022 by avibootz

Related questions

1 answer 72 views
72 views asked Jul 7, 2020 by avibootz
1 answer 46 views
1 answer 49 views
1 answer 39 views
3 answers 78 views
...