Transpose of a matrix

In this post I would be discussing a method to determine the transpose of a matrix. The transpose AT of a matrix A can be obtained by reflecting the elements along its main diagonal. In other words, transpose of a matrix means to interchange the rows and columns of a matrix. Repeating the process on the transposed matrix returns the elements to their original position.

transpose of a matrix

transpose of a matrix

Please note that we are interested in modifying the array to store the transpose of a matrix (array) and not simply printing the array by interchanging the inner and outer loops. The idea is to design a function which would accept an array as argument and then return an array after transposing the array. The idea behind returning an array from the function, is that it would enable the user to use the array for some purpose other than printing also.

In case the array to be transposed is a square array, it can be transposed in-place, meaning no second array is required. In case the array to be transposed is a rectangular array, then another array would be required to hold the transpose of a matrix.

The Java program to find the transpose of a matrix is as follows:

class Transpose{
    public static void main( String args[] ){
        int square[][] = {  { 1, 2, 3 },
                            { 4, 5, 6 },
                            { 7, 8, 9 } };
        square = transpose( square );
        display( square );
        int rectangle[][] = { { 1, 2, 3, 4 },
                              { 5, 6 ,7, 8 },
                              { 9, 10, 11, 12 } };
        rectangle = transpose( rectangle );
        display( rectangle );
    }

    public static int[][] transpose( int a[][] ){
        if( a.length == a[0].length ){
            int temp;
            for( int row = 0; row < a.length ; row++ ){
                for( int col=0; col < row; col++ ){
                    temp = a[ row ][ col ];
                    a[ row ][ col ] = a[ col ][ row ];
                    a[ col ][ row ] = temp;
                }
            }
            return a;
        }else{
            int ans[][] = new int[ a[0].length ][ a.length ];
            for( int row = 0; row < ans.length ; row++ ){
                for( int col=0; col < ans[row].length; col++ ){
                    ans[row][col] = a[ col ][ row ];
                }
            }
            return ans;
        }

    }
    public static void display( int a[][] ){
        for( int row = 0; row < a.length ; row++ ){
            for( int col=0; col < a[ row ].length; col++ ){
                System.out.print( "\t" + a[ row ][ col ] );
            }
            System.out.println();
        }
    }
}

As usual, the main function has purposely been kept to minimum and its expected that students will write appropriate input/output statements as per the requirement.