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
2010-04-21 06:23:25
+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
2010-04-21 06:23:52
+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
2010-04-21 06:25:58
+1
A:
Why bother ? Just swap indices in any access statement.
High Performance Mark
2010-04-21 06:38:00
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
2010-04-21 07:29:22
A:
Wikipedia had an article In-place matrix transposition. The article covers non-square matrices.
dlb
2010-04-21 21:37:32
A:
Has nobody except from dlb noticed that the algorithm is different for non-square matrices?
Albus Dumbledore
2010-10-01 07:41:47