Transposing a matrix deals with the same matrix with some modifications. Here,the rows become columns and columns became rows.
To implement this concept in java, follow the below steps.
Logic:
- First, get the dimensions for the matrix from the user.
- Read the elements of the input matrix.
- Create the transpose matrix structure.
- Using two for loops, change the columns into rows and rows into columns.
- Finally, print the transpose matrix as output.
Program:
import java.util.Scanner;
public class TransposeMatrixEg {
public static void
main(String[] args) {
Scanner s1 = new
Scanner(System.in);
System.out.print("Enter rows for the matrix: ");
int rows =
s1.nextInt();
System.out.print("Enter columns for the matrix: ");
int cols =
s1.nextInt();
// read the
input for Matrix
System.out.println("Enter the elements for the matrix:");
for (int i =
0; i < rows; i++) {
for (int j
= 0; j < cols; j++) {
matrix_1[i][j] = s1.nextInt();
}
}
//Tranpose
matrix initialisation and conversion
int[][]
transpose = new int[cols][rows];
for (int i =
0; i < rows; i++) {
for (int j
= 0; j < cols; j++) {
transpose[j][i] = matrix_1[i][j];
}
}
System.out.println("Transpose of the matrix:");
for (int i =
0; i < cols; i++) {
for (int j
= 0; j < rows; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
}
}
Output:
Compile and
run the program to get the output.
C:\raji\blog>javac TransposeMatrixEg.java
C:\raji\blog>java TransposeMatrixEg
Enter rows for the matrix: 3
Enter columns for the matrix: 3
Enter the elements for the matrix:
1
2
3
4
5
6
7
8
9
Transpose of the matrix:
1 4 7
2 5 8
3 6 9
This is the way of creating the java program to implement
the transpose matrix. Hope this blog is useful to you. Keep coding!!!