Multi-dimensional array transposing

I saw that all of the answers create a new resultant matrix. This is simple:

matrix[i][j] = matrix[j][i];

However, you can also do this in-place, in case of square matrix.

// Transpose, where m == n
for (int i = 0; i < m; i++) {
    for (int j = i + 1; j < n; j++) {
        int temp = matrix[i][j];
        matrix[i][j] = matrix[j][i];
        matrix[j][i] = temp;
    }
}

This is better for larger matrices, where creating a new resultant matrix is wasteful in terms of memory. If its not square, you can create a new one with NxM dimensions and do the out of place method. Note: for in-place, take care of j = i + 1. It’s not 0.

Leave a Comment