6

how to transpose a 2D matrix in place?

Ikke
  • 95,379
  • 23
  • 93
  • 119
Jony
  • 6,514
  • 20
  • 57
  • 70

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
  • 40,547
  • 20
  • 99
  • 126
  • 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
  • 24,655
  • 6
  • 74
  • 116
  • 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
  • 429,241
  • 80
  • 483
  • 523
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
  • 91,013
  • 29
  • 181
  • 233
dimmat
  • 197
  • 1
  • 2
  • 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
  • 75,673
  • 7
  • 99
  • 152
  • 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
  • 550
  • 11
  • 18