how to transpose a 2D matrix in place?
Asked
Active
Viewed 1.1k times
6
-
3square or not? it makes a big difference – Anycorn Apr 21 '10 at 06:34
-
1@aaa: Transposing a non-square matrix in place does not make a lot of sense. – Jens Apr 21 '10 at 07:29
-
2Though depending on the representation (for example using a single array of N*M dimensions) it could be done. – Matthieu M. Apr 21 '10 at 13:52
-
1This was pretty much "beaten to death" in [this post](http://stackoverflow.com/questions/3062974/in-place-permutation-of-a-array-follows-this-rule) – NealB Nov 08 '11 at 20:39
-
@Jens It makes a lot of sense if you store all matrix data in one single array. – Waruyama Jan 15 '20 at 10:15
8 Answers
7
Wikipedia had an article In-place matrix transposition. The article covers non-square matrices.

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
-
3WARNING! 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
-
1This 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
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
-
11There 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