Advertisement
Cinestra

Matrix Multiply

Jan 13th, 2023
995
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void matrix_multiply(int table1[][2], int rows1, int columns1, int table2[][2], int rows2, int columns2, int result[][2])
  5. {
  6.     if (columns1 != rows2)
  7.     {
  8.         cout << "Matrix Multiplication not possible";
  9.     }
  10.  
  11.     if (columns1 == rows2)
  12.     {
  13.  
  14.         //If two matrices are being muiltiplied [m][n] and [n][p] then the resulting matrix is [m][p]
  15.  
  16.         //Start by initializing array at 0
  17.         for (int m = 0; m < rows1; m++)
  18.         {
  19.             for (int p = 0; p < columns2; p++)
  20.             {
  21.                 result[m][p] = 0;
  22.             }
  23.         }
  24.  
  25.         for (int i = 0; i < rows1; i++)
  26.         {
  27.             for (int j = 0; j < columns2; j++)
  28.             {
  29.                 for (int k = 0; k < columns1; k++)
  30.                     result[i][j] += table1[i][k] * table2[k][j];
  31.             }
  32.         }
  33.     }
  34. }
  35.  
  36. void print_matrix(int matrix[][2], int rows, int columns)
  37. {
  38.     for (int i = 0; i < rows; i++)
  39.     {
  40.         for (int j = 0; j < columns; j++)
  41.         {
  42.             cout << matrix[i][j] << " ";
  43.         }
  44.     }
  45. }
  46.  
  47. int main()
  48. {
  49.     int table1[2][2];
  50.     table1[0][0] = 1;
  51.     table1[0][1] = 2;
  52.     table1[1][0] = 3;
  53.     table1[1][1] = 4;
  54.     print_matrix(table1, 2, 2);
  55.  
  56.     cout << endl;
  57.  
  58.     int table2[2][2];
  59.     table2[0][0] = 1;
  60.     table2[0][1] = 2;
  61.     table2[1][0] = 2;
  62.     table2[1][1] = 1;
  63.     print_matrix(table2, 2, 2);
  64.  
  65.     cout << endl;
  66.  
  67.     int result[2][2]; // If two matrices are being multiplied [m][n] and [n][p]. [n] and [n] must be the same. The resulting Matrix is [m][p].
  68.     matrix_multiply(table1, 2, 2, table2, 2, 2, result);
  69.     print_matrix(result, 2, 2);
  70.  
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement