矩阵乘法算法

在本节中,我们将看到如何将两个矩阵相乘。如果满足此条件,则只能执行矩阵乘法。假设两个矩阵是A和B,并且它们的维度分别是A(mxn)和B(pxq),则当且仅当n = p时,才能找到所得矩阵。然后,所得矩阵C的阶数将为(mxq)。

算法

matrixMultiply(A, B):
Assume dimension of A is (m x n), dimension of B is (p x q)
Begin
   if n is not same as p, then exit
   otherwise define C matrix as (m x q)
   for i in range 0 to m - 1, do
      for j in range 0 to q – 1, do
         for k in range 0 to p, do
            C[i, j] = C[i, j] + (A[i, k] * A[k, j])
         done
      done
   done
End

示例

#include<iostream>
using namespace std;
int main() {
   int product[10][10], r1=3, c1=3, r2=3, c2=3, i, j, k;
   int a[3][3] = {
      {2, 4, 1},
      {2, 3, 9},
      {3, 1, 8}
   };
   int b[3][3] = {
      {1, 2, 3},
      {3, 6, 1},
      {2, 4, 7}
   };
   if (c1 != r2) {
      cout<<"Column of first matrix should be equal to row of second matrix";
   } else {
      cout<<"第一个矩阵是:"<<endl;
      for(i=0; i<r1; ++i) {
         for(j=0; j<c1; ++j)
            cout<<a[i][j]<<" ";
         cout<<endl;
      }
      cout<<endl;
      cout<<"第二个矩阵是:"<<endl;
      for(i=0; i<r2; ++i) {
         for(j=0; j<c2; ++j)
            cout<<b[i][j]<<" ";
         cout<<endl;
      }
      cout<<endl;
      for(i=0; i<r1; ++i)
         for(j=0; j<c2; ++j) {
            product[i][j] = 0;
         }
      for(i=0; i<r1; ++i)
         for(j=0; j<c2; ++j)
            for(k=0; k<c1; ++k) {
               product[i][j]+=a[i][k]*b[k][j];
            }
      cout<<"这两个矩阵的乘积为:"<<endl;
      for(i=0; i<r1; ++i) {
         for(j=0; j<c2; ++j)
            cout<<product[i][j]<<" ";
         cout<<endl;
      }
   }
   return 0;
}

输出结果

第一个矩阵是:
2 4 1
2 3 9
3 1 8
第二个矩阵是:
1 2 3
3 6 1
2 4 7
这两个矩阵的乘积为:
16 32 17
29 58 72
22 44 66