find transpose of a matrix in java

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

In this post, we will see how to find transpose of matrix in java.
Transpose of matrix?
A matrix which is created by converting all the rows of a given matrix into columns and vice-versa.
Below image shows example of matrix transpose.

So as you can see we have converted rows to columns and vice versa.

Java program to find transpose of matrix:

package org.arpit.java2blog;

/**
@author Arpit Mandliya
 */
public class TransposeMatrixMain {
 public static void main(String args[]) {
 // initialize the variable
 int[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 },{10, 11, 12} };

 // This will store resultant transpose matrix
 int[][] transposeMtrx=new int[a[0].length][a.length];
 // print the original matrix
 System.out.println("Original matrix:");
 for (int i = 0; i < 4; i++) {
 for (int j = 0; j < 3; j++) {
 System.out.print(" "+a[i][j]);
 }
 System.out.println();
 }

 // Performing transpose operation
 for (int i = 0; i < 4; i++) {
 for (int j = 0; j < 3; j++) {
 transposeMtrx[j][i] = a[i][j];
 }
 }
 System.out.println("======================");
 System.out.println("Transpose matrix:");
 // print transpose matrix
 for (int i = 0; i < 3; i++) {
 for (int j = 0; j < 4; j++) {
 System.out.print(" "+transposeMtrx[i][j]);
 }
 System.out.println();
 }
 }
}

When you run above program, you will get below output:

Original matrix:
 1 2 3
 4 5 6
 7 8 9
 10 11 12
======================
Transpose matrix:
 1 4 7 10
 2 5 8 11
 3 6 9 12
[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.