C++程式:透過函式傳遞矩陣實現矩陣相乘
矩陣是由數字組成的矩形陣列,以行和列的形式排列。
矩陣示例如下所示。
一個3*4矩陣有3行4列,如下所示。
8 6 3 5 7 1 9 2 5 1 9 8
一個透過函式傳遞矩陣來實現矩陣相乘的程式如下所示。
示例
#include<iostream>
using namespace std;
void MatrixMultiplication(int a[2][3],int b[3][3]) {
int product[10][10], r1=2, c1=3, r2=3, c2=3, i, j, k;
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;
}
}
}
int main() {
int a[2][3] = { {2, 4, 1} , {2, 3, 9} };
int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 9, 7} };
MatrixMultiplication(a,b);
return 0;
}輸出
The first matrix is: 2 4 1 2 3 9 The second matrix is: 1 2 3 3 6 1 2 9 7 Product of the two matrices is: 16 37 17 29 103 72
在上面的程式中,兩個矩陣a和b在main()函式中初始化如下。
int a[2][3] = { {2, 4, 1} , {2, 3, 9} };
int b[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 9, 7} };使用a和b的值呼叫MatrixMultiplication()函式。如下所示。
MatrixMultiplication(a,b);
在MatrixMultiplication()函式中,如果第一個矩陣的列數不等於第二個矩陣的行數,則無法進行乘法運算。在這種情況下,會列印錯誤訊息。如下所示。
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迴圈來計算兩個矩陣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;
}
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP