Khoa Dumbo Le Khoa Dumbo Le - 9 days ago 4
C Question

Need someone to illustrate this code matrix transpose

The matrix should be like n x-axes and m y-axes.

for(int z = 0; z < m; z++){
for(int x = 0; x < n; x++){
transB[x * m + z] = B[z*n + x];
}
}


Can someone explain before and after transponating according to the code? I'm having a hard time illustrating, how it looks like.

Answer

Is this what you (or somebody else) intended? Revised: (from Jonathan Leffler)

#include <stdio.h>

#define WIDTH 3
#define DEPTH 4

int main(void)
{
    int array[WIDTH*DEPTH] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
    int trans[DEPTH*WIDTH];

    for(int i=0; i<WIDTH*DEPTH; i++) {
        printf("%-3d", array[i]);
        if((i+1) % WIDTH == 0) {
            printf("\n");
        }
    }
    printf("\n");

    for(int z = 0; z < DEPTH; z++) {
        for(int x = 0; x < WIDTH; x++) {  
            trans[x * DEPTH + z] = array[z * WIDTH + x];
        } 
    }

    for(int i=0; i<WIDTH*DEPTH; i++) {
        printf("%-3d", trans[i]);
        if((i+1) % DEPTH == 0) {
            printf("\n");
        }
    }

    return 0;
}

Program output:

1  2  3
4  5  6
7  8  9
10 11 12

1  4  7  10
2  5  8  11
3  6  9  12

The point being that you use the matrix width to find the position in a 1-D array. You might use a similar technique when processing an image file, where you read the pixel data as a 1-D array.

A 1-D array is usually accessed as 2-D with (row * width) + column although it is less easy to read when the width and depth have been swapped.

Comments