Skip to content

Instantly share code, notes, and snippets.

@juanfal
Last active November 23, 2023 09:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanfal/37aac4e61e052185136417c9a3f071d9 to your computer and use it in GitHub Desktop.
Save juanfal/37aac4e61e052185136417c9a3f071d9 to your computer and use it in GitHub Desktop.
matrix mult general
// t13e10.multMat.cpp
// juanfc 2023-11-23
// https://gist.github.com/37aac4e61e052185136417c9a3f071d9
#include <iostream>
#include <array>
using namespace std;
const int K = 5;
const int M = 4;
const int N = 3;
typedef array<array<int, M>,N> TMatNm;
typedef array<array<int, K>,M> TMatmK;
typedef array<array<int, K>,N> TMatNK;
int main()
{
TMatNK mult(TMatNm, TMatmK);
void printMat(TMatNm);
void printMat(TMatmK);
void printMat(TMatNK);
TMatNm a = {{
{{1, 2, 3, 4}},
{{1, 2, 3, 4}},
{{1, 2, 3, 4}}
}};
TMatmK b = {{
{{1, 0, 0, 0, 0}},
{{0, 1, 0, 0, 0}},
{{0, 0, 1, 0, 0}},
{{0, 0, 0, 1, 0}}
}};
cout << "a: " << endl;
printMat(a);
cout << "b: " << endl;
printMat(b);
cout << "a x b: " << endl;
printMat(mult(a, b));
return 0;
}
TMatNK mult(TMatNm a, TMatmK b)
{
TMatNK res;
for (int r = 0; r < N; ++r)
for (int c = 0; c < K; ++c) {
res[r][c] = 0;
for (int i = 0; i < M; ++i)
res[r][c] += a[r][i] * b[i][c];
}
return res;
}
void printMat(TMatNm m)
{
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j)
cout << m[i][j] << " ";
cout << endl;
}
cout << endl;
}
void printMat(TMatmK m)
{
for (int i = 0; i < M; ++i) {
for (int j = 0; j < K; ++j)
cout << m[i][j] << " ";
cout << endl;
}
cout << endl;
}
void printMat(TMatNK m)
{
for (int i = 0; i < N; ++i) {
for (int j = 0; j < K; ++j)
cout << m[i][j] << " ";
cout << endl;
}
cout << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment