C++ 程式執行矩陣乘法
矩陣是用行和列形式排列的數字矩形陣列。
以下是矩陣的示例。
3*2 矩陣有 3 行和 2 列,如下所示 −
8 1 4 9 5 6
一個執行矩陣乘法的程式如下。
示例
#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<<"The first matrix is:"<<endl; for(i=0; i<r1; ++i) { for(j=0; j<c1; ++j) cout<<a[i][j]<<" "; cout<<endl; } cout<<endl; cout<<"The second matrix is:"<<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<<"Product of the two matrices is:"<<endl; for(i=0; i<r1; ++i) { for(j=0; j<c2; ++j) cout<<product[i][j]<<" "; cout<<endl; } } return 0; }
輸出
The first matrix is: 2 4 1 2 3 9 3 1 8 The second matrix is: 1 2 3 3 6 1 2 4 7 Product of the two matrices is: 16 32 17 29 58 72 22 44 66
在上述程式中,兩個矩陣 a 和 b 初始化如下 −
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"; }
使用巢狀 for 迴圈顯示矩陣 a 和 b。以下程式碼片段對此進行了演示。
cout<<"The first matrix is:"<<endl; for(i=0; i<r1; ++i) { for(j=0; j<c1; ++j) cout<<a[i][j]<<" "; cout<<endl; } cout<<endl; cout<<"The second matrix is:"<<endl; for(i=0; i<r2; ++i) { for(j=0; j<c2; ++j) cout<<b[i][j]<<" "; cout<<endl; } cout<<endl;
在此之後,product[][] 矩陣初始化為 0。然後使用巢狀 for 迴圈查詢 2 個矩陣 a 和 b 的乘積。這在下面的程式碼片段中進行了演示。
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<<Product of the two matrices is:"<<endl; for(i=0; i<r1; ++i) { for(j=0; j<c2; ++j) cout<<product[i][j]<<" "; cout<<endl; }
廣告