เมทริกซ์สองตัวสามารถคูณกันได้ (Multiplicable) ก็ต่อเมื่อจำนวนคอลัมน์ของเมทริกซ์ตัวแรกเท่ากับจำนวนแถวของเมทริกซ์ตัวที่สอง ตัวอย่าง:
แถวของเมทริกซ์ 1 = 3, คอลัมน์ของเมทริกซ์ 1 = 2 แถวของเมทริกซ์ 2 = 2, คอลัมน์ของเมทริกซ์ 2 = 5 เมทริกซ์ 1 และ 2 คูณกันได้ เนื่องจากคอลัมน์ของเมทริกซ์ 1 = แถวของเมทริกซ์ 2 (2 = 2)
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
int main() {
int row1, column1, row2, column2;
cout << "Enter the dimensions of the first matrix:" << endl;
cin >> row1;
cin >> column1;
cout << "Enter the dimensions of the second matrix: " << endl;
cin >> row2;
cin >> column2;
cout << "First Matrix" << endl;
cout << "Number of rows: " << row1 << endl;
cout << "Number of columns: " << column1 << endl;
cout << "Second Matrix" << endl;
cout << "Number of rows: " << row2 << endl;
cout << "Number of columns: " << column2 << endl;
if (column1 == row2)
cout << "Matrices are multiplicable";
else
cout << "Matrices are not multiplicable";
return 0;
}
ผลลัพธ์
Enter the dimensions of the first matrix: 2 3 Enter the dimensions of the second matrix: 3 3 First Matrix Number of rows: 2 Number of columns: 3 Second Matrix Number of rows: 3 Number of columns: 3 Matrices are multiplicable
อธิบายโค้ด
รับขนาดเมทริกซ์ทั้งสองจากผู้ใช้:
cout<<"Enter the dimensions of the first matrix:"<< endl; cin>>row1; cin>>column1; cout<<"Enter the dimensions of the second matrix: "<<endl; cin>>row2; cin>>column2;
แสดงขนาดเมทริกซ์:
cout<<"First Matrix"<<endl; cout<<"Number of rows: "<<row1<<endl; cout<<"Number of columns: "<<column1<<endl; cout<<"Second Matrix"<<endl; cout<<"Number of rows: "<<row2<<endl; cout<<"Number of columns: "<<column2<<endl;
ตรวจสอบเงื่อนไขการคูณ:
if(column1 == row2)
cout<<"Matrices are multiplicable";
else
cout<<"Matrices are not multiplicable";