views:

264

answers:

6

how to transpose a 2D matrix in place?

+1  A: 
for (int i=0; i<n; i++) {
  for (int j=0; j<i; j++) {
    temp = a[i][j];
    a[i][j] = a[j][i];
    a[j][i] = temp;
  }
}
Simon Nickerson
+2  A: 

You have not specified a language, but generally, what you do is:

let a be your array.
for each i,j with i<j switch a[i,j] with a[j,i]
Jens
+2  A: 

To get the transpose of a square matrix we need to consider elements above the main diagonal or below it and swap each with its reflection along the main diagonal:

for i->0 to N
 for j->i+1 to N
  swap matrix[i][j] with matrix[j][i]
codaddict
+1  A: 

Why bother ? Just swap indices in any access statement.

High Performance Mark
There is a serious performance penalty for accessing 2D arrays in the "wrong" order - it's often better to pay the price of a transpose in order to get the benefits of contiguous memory access (unit stride).
Paul R
A: 

Wikipedia had an article In-place matrix transposition. The article covers non-square matrices.

http://en.wikipedia.org/wiki/In-place_matrix_transposition

dlb
A: 

Has nobody except from dlb noticed that the algorithm is different for non-square matrices?

Albus Dumbledore