Matrix multiplication combines two matrices into a new one, written as . The first matrix’s column count must match the second matrix’s row count. The result has the first matrix’s rows and the second matrix’s columns. Unlike ordinary numbers, changing the order can change the result. See matrix algebra for the rules.
Definition
If is an matrix and is an matrix, then:
The matrix product is an matrix:
Each entry in is calculated as:
where and .
Code Implementation
Here is a simple implementation of matrix multiplication in C++:
#include <iostream>
#include <vector>
using namespace std;
using Matrix = vector<vector<int>>;
Matrix matmul(const Matrix& a, const Matrix& b) {
int m = a.size(), n = a[0].size(), p = b[0].size();
Matrix c(m, vector<int>(p, 0));
for (int i = 0; i < m; ++i) for (int j = 0; j < p; ++j) for (int k = 0; k < n; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
return c;
}
int main(void) {
Matrix a = {{1, 2, 3}, {4, 5, 6}};
Matrix b = {{7, 8}, {9, 10}, {11, 12}};
Matrix c = matmul(a, b);
for (const auto& row : c) {
for (int val : row) cout << val << " ";
cout << endl;
}
return 0;
}