Java Program to Transpose Matrix

Write a Java Program to Transpose Matrix with an example. Or Java Program to convert rows into columns in a given Matrix or multi-dimensional array. Matrix Transpose is converting rows into columns and columns into rows. 

In this Java Transpose Matrix example, we declared a 3 * 3 org_arr integer matrix with random values, and another one to store the transposed matrix. Next, we used for loop to iterate the org_arr Matrix items. Within the for loop, we assigned the org_arr Matrix rows to tras_arr columns.

public class TransposeMatrix {
	public static void main(String[] args) {
		
		int i, j;	
		
		int[][] org_arr = {{15, 25, 35}, {45, 55, 65}, {75, 85, 95}};
		int[][] trans_arr = new int[3][3];
		

		for(i = 0; i < org_arr.length ; i++)
		{
			for(j = 0; j < org_arr[0].length; j++)
			{
				trans_arr[j][i] = org_arr[i][j];
			}
		}
		
		System.out.println("\nOriginal Matrix Items are :");
		for(i = 0; i < org_arr.length ; i++)
		{
			for(j = 0; j < org_arr[0].length; j++)
			{
				System.out.format("%d \t", org_arr[i][j]);
			}
			System.out.print("\n");
		}
		
		System.out.println("\nAfter Transposing Matrix Items are :");
		for(i = 0; i < trans_arr.length ; i++)
		{
			for(j = 0; j < trans_arr[0].length; j++)
			{
				System.out.format("%d \t", trans_arr[i][j]);
			}
			System.out.print("\n");
		}
	}
}

Java Matrix transpose output

Original Matrix Items are :
15 	25 	35 	
45 	55 	65 	
75 	85 	95 	

After Transposing Matrix Items are :
15 	45 	75 	
25 	55 	85 	
35 	65 	95 	

Java Program to Transpose Matrix example 2

This Java Matrix Transpose code is the same as the above. However, this Transpose matrix Java code allows the user to enter the number of rows, columns, and the matrix items.

import java.util.Scanner;

public class TransposeMatrix {
	
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		int i, j, rows, columns;
		
		sc= new Scanner(System.in);
		
		System.out.println("\n Enter Matrix Rows and Columns :  ");
		rows = sc.nextInt();
		columns = sc.nextInt();
		
		int[][] org_arr = new int[rows][columns];
		int[][] trans_arr = new int[rows][columns];
		
		System.out.println("\n Please Enter the Sparse Matrix Items :  ");
		for(i = 0; i < rows; i++) {
			for(j = 0; j < columns; j++) {
				org_arr[i][j] = sc.nextInt();
			}		
		}

		for(i = 0; i < org_arr.length ; i++)
		{
			for(j = 0; j < org_arr[0].length; j++)
			{
				trans_arr[j][i] = org_arr[i][j];
			}
		}
		
		System.out.println("\nAfter Transposing Matrix Items are :");
		for(i = 0; i < trans_arr.length ; i++)
		{
			for(j = 0; j < trans_arr[0].length; j++)
			{
				System.out.format("%d \t", trans_arr[i][j]);
			}
			System.out.print("\n");
		}
	}
}
Java Program for Transpose Matrix 2