Is it possible to transpose a (m,n) matrix in-place, giving that the matrix is represented as a single array of size m*n ?
The usual algorithm
transpose(Matrix mat,int rows, int cols ){
//construction step
Matrix tmat;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
tmat[j][i] = mat[i][j];
}
}
}
doesn’t apply to a single array unless the matrix is a square matrix.
If none, what is the minimum amount of additional memory needed??
EDIT:
I have already tried all flavors of
for(int i=0;i<n;++i) {
for(int j=0;j<i;++j) {
var swap = m[i][j];
m[i][j] = m[j][i];
m[j][i] = swap;
}
}
And it is not correct. In this specific example, m doesnt even exist. In a single line
matrix mat[i][j] = mat[i*m + j], where trans[j][i] = trans[i*n + j]
Inspired by the Wikipedia – Following the cycles algorithm description, I came up with following C++ implementation:
The program makes the in-place matrix transposition of the 2 × 4 matrix
represented in row-major ordering
{0, 1, 2, 3, 4, 5, 6, 7}into the 4 × 2 matrixrepresented by the row-major ordering
{0, 4, 1, 5, 2, 6, 3, 7}.The argument
moftransposerepresents the rowsize, the columnsizenis determined by the rowsize and the sequence size. The algorithm needsm×nbits of auxiliary storage to store the information, which elements have been swapped. The indexes of the sequence are mapped with the following scheme:The mapping function in general is:
We can identify four cycles within this sequence:
{ 0 },{ 1, 2, 4 },{3, 5, 6}and{ 7 }. Each cycle can be transposed independent of the other cycles. The variablecycleinitially points to the second element (the first does not need to be moved because0 → 0). The bit-arrayvisitedholds the already transposed elements and indicates, that index 1 (the second element) needs to be moved. Index 1 gets swapped with index 2 (mapping function). Now index 1 holds the element of index 2 and this element gets swapped with the element of index 4. Now index 1 holds the element of index 4. The element of index 4 should go to index 1, it is in the right place, transposing of the cycle has finished, all touched indexes have been marked visited. The variablecyclegets incremented till the first not visited index, which is 3. The procedure continues with this cycle till all cycles have been transposed.