DEV Community

Cover image for Transposing a Matrix in Java
dous
dous

Posted on

Transposing a Matrix in Java

Sometimes you may need to transpose a matrix. For example while working on linear algebra. The main logic is writing the elements in matrix’s row as a column.

I choose Java to do this however you can use any language. If even the syntax changes, the main logic always will be the same.

Main method

Scanner sc = new Scanner(System.in); System.out.println("Row number:"); int row = sc.nextInt(); System.out.println("Column number:"); int col = sc.nextInt(); int[][] arr = new int[row][col]; for(int i = 0; i < arr.length; i++){ for(int j = 0; j < arr[0].length; j++){ System.out.println("Enter the arr["+i+"]["+j+"] element:"); arr[i][j] = sc.nextInt(); } } System.out.println(); print2dArr(arr); System.out.println(); print2dArr(tranpose(arr)); sc.close(); 
Enter fullscreen mode Exit fullscreen mode

Transpose Method

static int[][] tranpose(int[][] arr){ int[][] ret = new int[arr.length][arr[0].length]; for(int i = 0; i < arr.length; i++){ for(int j = 0; j < arr[0].length; j++){ ret[j][i] = arr[i][j]; } } return ret; } 
Enter fullscreen mode Exit fullscreen mode

Print Method

static void print2dArr(int[][] arr){ for(int i = 0; i < arr.length; i++){ for(int j = 0; j < arr[0].length; j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } } 
Enter fullscreen mode Exit fullscreen mode

Output

Row number: 3 Column number: 3 Enter the arr[0][0] element: 1 Enter the arr[0][1] element: 6 Enter the arr[0][2] element: 2 Enter the arr[1][0] element: 7 Enter the arr[1][1] element: 8 Enter the arr[1][2] element: 3 Enter the arr[2][0] element: 2 Enter the arr[2][1] element: 3 Enter the arr[2][2] element: 1 1 6 2 7 8 3 2 3 1 1 7 2 6 8 3 2 3 1 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)