Search code examples
javaalgorithmmatrixtransposein-place

In-place matrix transpose of an M*N matrix in Java not possible?


Is it possible to do in-place matrix transpose of an M*N matrix in Java? I don't think it's possible in Java because, in a 3*5 matrix, the element at 3*5 would ideally be swapped with the element at 5*3, but such a position does not exist. In say, C/C++, it would be possible since memory is contiguous.

Also, there are other algorithms like the one posted here for M*N matrices, which I believe are not applicable to Java, but how's it any different from swapping elements at A[i][j] with A[j][i] since even the rolling window algorithm in the link above takes auxiliary memory?


Solution

  • You have to be careful with the term in-place. Strictly speaking, the transpose operator 'creates' a new matrix with potentially new dimensions. In the case of the article you linked, in-place just means using the same memory for the initial and final matrices, which is of course possible with a clever representation.

    A trivial solution might be:

    public class Matrix {
        private int[][] backingArray;
        private boolean transposed;
        public Matrix(int[][] _backingArray) {
            this.backingArray = _backingArray
        }
    
        public Matrix(int[] data, rows, columns) {
            backingArray = new int[rows][columns]
            for (int i = 0; i < rows; i++)
                for (int j = 0; j < columns; j++)
                    backingArray[i][j] = data[i*columns + j]
        }
    
        public int getElement(i, j) {
            if (transposed)
                return backingArray[j][i];
            return backingArray[i][j];
        }
    
        public void transpose() {
            transpose = !transpose;
        }
    }
    

    EDIT: Corrected some bad syntax

    EDIT: Made it so that a 1-D matrix can be read in as per the OPs question (?)