เมทริกซ์คืออาร์เรย์ของตัวเลขสี่เหลี่ยมที่จัดเรียงในรูปแบบของแถวและคอลัมน์
ตัวอย่างของเมทริกซ์มีดังนี้
เมทริกซ์ 4*3 มี 4 แถว 3 คอลัมน์ดังแสดงด้านล่าง -
3 5 1 7 1 9 3 9 4 1 6 7
โปรแกรมที่บวกเมทริกซ์สองตัวโดยใช้อาร์เรย์หลายมิติมีดังนี้
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int r=2, c=4, sum[2][4], i, j;
int a[2][4] = {{1,5,9,4} , {3,2,8,3}};
int b[2][4] = {{6,3,8,2} , {1,5,2,9}};
cout<<"The first matrix is: "<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"The second matrix is: "<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(i=0;i<r;++i)
for(j=0;j<c;++j)
sum[i][j]=a[i][j]+b[i][j];
cout<<"Sum of the two matrices is:"<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<sum[i][j]<<" ";
cout<<endl;
}
return 0;
} ผลลัพธ์
The first matrix is: 1 5 9 4 3 2 8 3 The second matrix is: 6 3 8 2 1 5 2 9 Sum of the two matrices is: 7 8 17 6 4 7 10 12
ในโปรแกรมข้างต้น ขั้นแรกให้กำหนดเมทริกซ์ a และ b สองตัว ดังแสดงไว้ดังนี้
int a[2][4] = {{1,5,9,4} , {3,2,8,3}};
int b[2][4] = {{6,3,8,2} , {1,5,2,9}};
cout<<"The first matrix is: "<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"The second matrix is: "<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
} เมทริกซ์สองตัวถูกเพิ่มโดยใช้ nested for loop และผลลัพธ์จะถูกเก็บไว้ใน matrix sum[][] ซึ่งแสดงในข้อมูลโค้ดต่อไปนี้
for(i=0;i<r;++i) for(j=0;j<c;++j) sum[i][j]=a[i][j]+b[i][j];
หลังจากได้ผลรวมของเมทริกซ์ทั้งสองแล้ว มันจะถูกพิมพ์บนหน้าจอ ทำได้ดังนี้ −
cout<<"Sum of the two matrices is:"<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<sum[i][j]<<" ";
cout<<endl;
}