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

คำนวณเมทริกซ์ транспอร์ส (Transpose) ด้วยโปรแกรม C

เมทริกซ์ทรานสโพสคืออะไร?

เมทริกซ์ทรานสโพสคือเมทริกซ์ที่แถวและคอลัมน์สลับกัน คือ ถ้า A และ B เป็นเมทริกซ์ที่แถวของ B เท่ากับคอลัมน์ของ A แล้ว B คือทรานสโพสของ A

ตรรกะการคำนวณ

for (i = 0; i < m; i++)
    for (j = 0; j < n; j++)
        transpose[j][i] = matrix[i][j];

โปรแกรมที่ 1: ใช้ for loop ธรรมดา

#include <stdio.h>
int main() {
    int m, n, i, j, matrix[10][10], transpose[10][10];
    printf("Enter rows and columns: ");
    scanf("%d %d", &m, &n);
    printf("Enter elements of the matrix:\n");
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &matrix[i][j]);
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            transpose[j][i] = matrix[i][j];
    printf("Transpose of the matrix:\n");
    for (i = 0; i < n; i++) {
        for (j = 0; j < m; j++)
            printf("%d\t", transpose[i][j]);
        printf("\n");
    }
    return 0;
}

ผลลัพธ์

Enter rows and columns: 2 3
Enter elements of the matrix:
1 2 3
2 4 5
Transpose of the matrix:
1 2
2 4
3 5

โปรแกรมที่ 2: ใช้ #define กำหนดขนาด

#include <stdio.h>
#define ROW 2
#define COL 5
int main() {
    int i, j, mat[ROW][COL], trans[COL][ROW];
    printf("Enter matrix:\n");
    for (i = 0; i < ROW; i++)
        for (j = 0; j < COL; j++)
            scanf("%d", &mat[i][j]);
    for (i = 0; i < ROW; i++)
        for (j = 0; j < COL; j++)
            trans[j][i] = mat[i][j];
    printf("\nTranspose matrix:\n");
    for (i = 0; i < COL; i++) {
        for (j = 0; j < ROW; j++)
            printf("%d ", trans[i][j]);
        printf("\n");
    }
    return 0;
}

ผลลัพธ์

Enter matrix:
1 2 3 4 5
5 4 3 2 1
Transpose matrix:
1 5
2 4
3 3
4 2
5 1