6

how to transpose a 2D matrix in place?

Ikke
  • 99,403
  • 23
  • 97
  • 120
Jony
  • 6,694
  • 20
  • 61
  • 71

8 Answers8

7

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

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

dlb
  • 983
  • 7
  • 17
6
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
  • 42,159
  • 20
  • 102
  • 127
  • 3
    WARNING! This is only correct for square arrays. See @dlb's Wikipedia link below for a non-square matrix implementation. – Mayank Apr 07 '14 at 06:04
4

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
  • 25,229
  • 9
  • 75
  • 117
  • 1
    This too is only correct for a square matrix. Handling non-square matrices is surprisingly difficult. – Waruyama Jan 15 '20 at 10:14
2

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-1
 for j->i+1 to N-1
  swap matrix[i][j] with matrix[j][i]
codaddict
  • 445,704
  • 82
  • 492
  • 529
1
for(i=0;i<N;i++)
  for(j=0;j<N;j++)
    if(i!=j && j>i)
      {
        temp=a[i][j];
        a[i][j]=a[j][i];
        a[j][i]=temp;
      }  

(N is the size of your array)

Maroun
  • 94,125
  • 30
  • 188
  • 241
dimmat
  • 195
  • 1
  • 3
  • 10
0

in c#

string[,] Value;
//fill Value

//create transposed array
ValueAux = new string[Value.GetLength(1),Value.GetLength(0)];
for (i = 0; i < Value.GetLength(0); i++)
{
  for (j = 0; j < Value.GetLength(1); j++)
  {
    Valueaux[j, i] = Value[i, j];
  }
}

The result is in ValueAux

Biggum
  • 372
  • 2
  • 8
0

Why bother ? Just swap indices in any access statement.

High Performance Mark
  • 77,191
  • 7
  • 105
  • 161
  • 11
    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 Apr 21 '10 at 07:29
-1

This seems to work well:

function transpose(a)
{
  return Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });
}
JWally
  • 582
  • 11
  • 18