Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ หา Transpose ของเมทริกซ์


Transpose ของเมทริกซ์ คือเมทริกซ์ใหม่ที่แถวกลายเป็นคอลัมน์ และคอลัมน์กลายเป็นแถว

ตัวอย่าง เมทริกซ์ 3×2:

1 2
3 4
5 6

Transpose (2×3):

1 3 5
2 4 6

ตัวอย่างโค้ด

#include <iostream>
using namespace std;

int main() {
    int transpose[10][10], r=3, c=2, i, j;
    int a[3][3] = { {1, 2}, {3, 4}, {5, 6} };
    cout << "The matrix is:" << endl;
    for(i=0; i<r; ++i) {
        for(j=0; j<c; ++j)
            cout << a[i][j] << " ";
        cout << endl;
    }
    cout << endl;
    for(i=0; i<r; ++i)
        for(j=0; j<c; ++j)
            transpose[j][i] = a[i][j];
    cout << "The transpose of the matrix is:" << endl;
    for(i=0; i<c; ++i) {
        for(j=0; j<r; ++j)
            cout << transpose[i][j] << " ";
        cout << endl;
    }
    return 0;
}

ผลลัพธ์

The matrix is:
1 2
3 4
5 6
The transpose of the matrix is:
1 3 5
2 4 6

อธิบายขั้นตอน

1. กำหนดเมทริกซ์ a[3][2] แสดงผล:

int a[3][3] = { {1, 2}, {3, 4}, {5, 6} };
cout<<"The matrix is:"<<endl;
for(i=0; i<r; ++i) {
    for(j=0; j<c; ++j)
        cout<<a[i][j]<<" ";
    cout<<endl;
}

2. คำนวณ Transpose: transpose[j][i] = a[i][j] (สลับ index):

for(i=0; i<r; ++i)
    for(j=0; j<c; ++j)
        transpose[j][i] = a[i][j];

3. แสดง Transpose (ขนาดกลายเป็น c×r):

cout<<"The transpose of the matrix is:"<<endl;
for(i=0; i<c; ++i) {
    for(j=0; j<r; ++j)
        cout<<transpose[i][j]<<" ";
    cout<<endl;
}