Search code examples
javaarraysmatrixtranspose

Transposing matrices in Java


I think I am missing something fundamental here about Java, I am not sure why my code below do not work, my steps:

  1. the input is a 2x2 matrix,
  2. copy the original matrix,
  3. loop through rows then column,
  4. assign original matrix's column values to the rows of the transpose matrix.
static void transpose(int[][] matrix) {
    int[][] temp = matrix.clone();
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            matrix[i][j] = temp[j][i];
        }
    }
}

Solution

  • The problem is use the function clone() because that will create a new matrix sharing only row arrays.

    Using the same code style, that works:

    int[][] temp = new int[2][2];
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            temp[i][j] = matrix[j][i];
        }
    }
    

    Note that, as temp is an empty matrix, the comparsion will be temp = matrix.

    So this works for a simple 2x2 matrix, but if you need other dimensions, instead of

    int[][] temp = new int[2][2];
    

    Use

    int[][] temp = new int[matrix[0].length][matrix.length];
    

    By the way, update the reference memory of the matrix is not a good practice. I think your method should return temp matrix.

    An entire update, a better method could be this one. Is almost the same you have but it can accept diferent lengths.

    public static int[][] transpose(int [][] matrix){
        int[][] temp = new int[matrix[0].length][matrix.length];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                temp[j][i] = matrix[i][j];
            }
        }
        return temp;
    }