How to transpose a matrix (swap rows and columns) in Java

1 Answer

0 votes
public class Program {

    // Function to transpose a matrix
    public static int[][] transpose(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;

        int[][] result = new int[cols][rows];

        for (int i = 0; i < cols; i++) {
            for (int j = 0; j < rows; j++) {
                result[i][j] = matrix[j][i];
            }
        }

        return result;
    }

    public static void main(String args[]) {

        int matrix[][] = {
            {1, 2, 3, 5},
            {4, 5, 6, 1},
            {7, 8, 9, 0}
        };

        int[][] transposed = transpose(matrix);

        for (int i = 0; i < transposed.length; i++) {
            for (int j = 0; j < transposed[0].length; j++) {
                System.out.print(transposed[i][j] + " ");
            }
            System.out.println();
        }
    }
}



/*
run:

1 4 7 
2 5 8 
3 6 9 
5 1 0 

*/

 



answered Aug 20, 2021 by avibootz
edited 1 day ago by avibootz
...