Advertisement
-nodo-

Matrix

Jun 1st, 2021 (edited)
819
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. const int size = 3;
  6.  
  7. template<class T>
  8. void print(T matrix) {
  9.     cout << "[\n";
  10.  
  11.     for (int y = 0; y < size; ++y) {
  12.         cout << "\t[";
  13.         for (int x = 0; x + 1 < size; ++x)
  14.             cout << matrix[y][x] << ", ";
  15.         cout << matrix[y][size - 1] << "]";
  16.  
  17.         if (y + 1 == size) cout << "\n]\n";
  18.         else cout << ",\n";
  19.     }
  20. }
  21.  
  22. int** multiply(int a[][size], int b[][size]) {
  23.     int** c = new int*[size];
  24.     int sum;
  25.  
  26.     for (int i = 0; i < size; ++i) c[i] = new int[size];
  27.     for (int y = 0; y < size; ++y)
  28.     for (int x = 0; x < size; ++x) {
  29.         sum = 0;
  30.         for (int z = 0; z < size; ++z) sum += a[y][z] * b[z][x];
  31.         c[y][x] = sum;
  32.     }
  33.    
  34.     return c;
  35. }
  36.  
  37. int main() {
  38.     int a[][size] = {
  39.         {-1, -2, 3},
  40.         {0, 2, -1},
  41.         {-1, 3, 0}
  42.     };
  43.  
  44.     int b[][size] = {
  45.         {1, 5, 1},
  46.         {2, 1, 2},
  47.         {3, 2, 3}
  48.     };
  49.  
  50.     int** c = multiply(a, b);
  51.  
  52.     cout << "a = "; print(a); cout << "\n";
  53.     cout << "b = "; print(b); cout << "\n";
  54.     cout << "c = "; print(c); cout << endl;
  55.  
  56.     for(int i = 0; i < size; ++i)
  57.         delete[] c[i];
  58.     delete[] c;
  59.  
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement