Frank Liu
Frank Liu

Reputation: 5

Unclear on 2D Matrix Transposal Method

How would one go about transposing a 2D matrix in this following manner?:

I understand that there is some sort of pattern to doing this but hard-coding is not the way, so if someone can provide some advice that would be great.

Original:

4 5 2 0

7 2 1 4

9 4 2 0

7 8 9 3

into

Transpose:

3 0 4 0

9 2 1 2

8 4 2 5

7 9 7 4

Upvotes: 0

Views: 50

Answers (1)

Razvan Meriniuc
Razvan Meriniuc

Reputation: 182

for(i=1; i<=n; i++) {
    for(j=1; j<=n-i; j++) {
        aux = a[i][j];
        a[i][j] = a[n-j+1][n-i+1];
        a[n-j+1][n-i+1] = aux;
    }

}

By looking at the matrix you can see that line i is swapped with column n-i+1, which is equivalent to the symmetrical elements relative to the second diagonal being swapped.

Upvotes: 1

Related Questions