How to multiply two matrices
Overview
To multiply two matrices, the rows of the first matrix must be equal to the number of columns of the second matrix. Matrix multiplication is a dot product.
Let’s understand this with the help of a diagram.
Example
#include <iostream>using namespace std;#define size 3 // number of rows and columnvoid matixMultiplicaion(int MatrixA[][size], int MatrixB[][size]) {int result[size][size]; // declare result matrix 3 X 3for (int i = 0; i < size; i++) { // handle rowsfor (int j = 0; j < size; j++) { // handle columnresult[i][j] = 0; // assign default valuefor (int k = 0; k < size; k++) { // compute dot product of matrixresult[i][j] += MatrixA[i][k] * MatrixB[k][j];}cout << result[i][j] << " "; // print the resultan matrix}cout << endl;}}int main() {int MatrixA[size][size] = { // declare Matrix A 3x3{1, 1, 1},{2, 2, 2},{3, 3, 3},};int MatrixB[size][size] = { // declare Matrix B 3X3{1, 1, 1},{2, 2, 2},{3, 3, 3},};/* since it is square matrix the row andcolumn size are same so we do not need to checkthe row and column are equal or not*/matixMultiplicaion(MatrixA, MatrixB);return 0;}
Explanation
- Line 6: We implement the function
matixMultiplicaion. - Line 21–30: We declare two matrices,
MatrixAandMatrixB. - Line 36: We call the
matixMultiplicaionfunction.