# Multiply 2 matrices

Oct 21st, 2020
531
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. #include <iostream>
2. #include <vector>
3.
4. template <typename T>
5. struct Matrix
6. {
7.     int nDim_n = 0, nDim_m = 0;
8.     std::vector<std::vector<T>> MAT;
9.
11.     void ReserveMatrix();
13.     void Print();
14.
15.     Matrix MatMultiplyMat(Matrix rhs, bool print);
16.     bool checkCompatibility(Matrix rhs);
17. };
18. int main()
19. {
20.     Matrix<int> M1, M2;
23.     std::cout << "M1 M2 \n";
24.     M1.MatMultiplyMat(M2, true);
25.     std::cout << "M2 M1 \n";
26.     M2.MatMultiplyMat(M1, true);
27. }
28.
29. template <typename T>
31. {
32.     std::cout << "Number of lines of Matrix " << nCountOfMatrix << "?\n";
33.     std::cin >> nDim_n;
34.     std::cout << "Number of columns of Matrix " << nCountOfMatrix << "?\n";
35.     std::cin >> nDim_m;
36.
37.     ReserveMatrix();
39. }
40.
41. template <typename T>
42. void Matrix<T>::ReserveMatrix()
43. {
44.     MAT.resize(nDim_n);
45.     for (auto& v : MAT)
46.         v.resize(nDim_m);
47. }
48.
49. template <typename T>
51. {
52.     for (auto& v : MAT)
53.         for (auto& x : v)
54.             std::cin >> x;
55. }
56.
57. template <typename T>
58. bool Matrix<T>::checkCompatibility(Matrix<T> rhs)
59. {
60.     return (nDim_m == rhs.nDim_n);
61. }
62.
63. template <typename T>
64. Matrix<T> Matrix<T>::MatMultiplyMat(Matrix<T> rhs, bool print)
65. {
66.     Matrix<T> result;
67.     if (checkCompatibility(rhs))
68.     {
69.         result.nDim_n = nDim_n;
70.         result.nDim_m = rhs.nDim_m;
71.         result.ReserveMatrix();
72.
73.         for (int i = 0; i < nDim_n; ++i)
74.         {
75.             for (int j = 0; j < rhs.nDim_m; ++j)
76.             {
77.                 T value = 0;
78.                 for(int k = 0; k < nDim_m; ++k)
79.                     value += MAT[i][k] * rhs.MAT[k][j];
80.                 result.MAT[i][j] = value;
81.             }
82.         }
83.
84.         if (print)
85.             result.Print();
86.     }
87.     else
88.     {
89.         std::cout << "Cannot multiply these two!";
90.     }
91.     return result;
92. }
93. template <typename T>
94. void Matrix<T>::Print()
95. {
96.     for (auto& v : MAT)
97.     {
98.         for (auto& x : v)
99.             std::cout << x << " ";
100.         std::cout << "\n";
101.     }
102.     std::cout << "\n";
103. }
104.
105.
106.
RAW Paste Data