Transpose of Matrix in Java

You are given a M * N matrix, find Transpose of Matrix. Transpose of matrix is obtained by interchanging rows and columns of a matrix that is by changing rows to columns and columns to rows.

Finding transpose of Matrix is very simple.

You are given a M * N matrix, find Transpose of Matrix. Transpose of matrix is obtained by interchanging rows and columns of a matrix that is by changing rows to columns and columns to rows.

**Lets understand the problem statement graphically and it will be more clear,**### Algorithm

Finding transpose of Matrix is very simple.

**Transpose of given matrix can be obtained by changing its rows to columns and columns to rows.**- Create a Transpose Matrix of,

Rows = Total column of original matrix.

Column = Total rows of original matrix. - Iterate through Original matrix, and fill Transpose Matrix data by interchanging rows to column and column to rows as shown below,
**TransposeMatrix[col][row] = OriginalMatrix[row][col].**

### Java Program to find Transpose of Matrix

package matrix; public class TransposeOfMatrix { public static void main(String[] args) { new TransposeOfMatrix(); } public TransposeOfMatrix() { int[][] matrix = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15} }; System.out.println("Before Transpose"); printMatrix(matrix); int[][] transposeMatrix = new int[matrix[0].length][matrix.length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { transposeMatrix[j][i] = matrix[i][j]; } } System.out.println("\nAfter Transpose"); printMatrix(transposeMatrix); } private void printMatrix(int[][] matrix){ for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }

### You may also like to see

#### Count zeros in a row wise and column wise sorted matrix

#### Implement Stack using Queue

#### Find Largest and Smallest number in Array

#### Find middle element of a linked list

#### Union and Intersection of Two Sorted Arrays

#### Merge two sorted arrays in Java

#### How is ambiguous overloaded method call resolved in java

**Enjoy !!!!**

**If you find any issue in post or face any error while implementing, Please comment.**

## Post a Comment