The transposition of a matrix is one of the most commonly studied questions in school or collages when learning Java Programs in practical labs.
In the transposition of a matrix we are supposed to flip the matrix over its diagonal, i.e. the rows of the original matrixbecome the columns and the columns of the original matrix become the rows of the transposed matrix.
Pseudo Logic Building
First we declare a 2-dimensional array to represent a matrix.
We add the values to the elements of the array.
We find the dimension of the matrix - rows and column size.
Create a new array (matrix) of the swapped dimensions - rows of our original array becomes columns and columns as row.
Finally we loop the rows and columns of the original matrix and add these elements to the column and row of the transposed matrix.
Finally we print our transposed matrix.
Java Program To Transpose A Matix
package org.code2care.java.arrays.examples;
import java.util.Arrays;
/**
* Java Program to transpose a
* Matrix
* <p>
* Author: Code2care.org
* Date: 28 Apr 2023
*/
public class JavaMatrixTranspose {
public static void main(String[] args) {
//2-D Matrix
int[][] originalMatrix = {
{1, 4},
{2, 5},
{3, 6}
};
int matrixRows = originalMatrix.length;
int matrixCols = originalMatrix[0].length;
//New matrix to store the transposed rows and columns
int[][] transpose = new int[matrixCols][matrixRows];
for (int i = 0; i < matrixRows; i++) {
for (int j = 0; j < matrixCols; j++) {
//copy into transposed originalMatrix
transpose[j][i] = originalMatrix[i][j];
}
}
System.out.println("Input Matrix:");
Arrays.stream(transpose)
.forEach(row -> {
Arrays.stream(row)
.forEach(element -> System.out.print(element + " "));
System.out.println();
});
System.out.println("Transposed Matrix:");
Arrays.stream(originalMatrix)
.forEach(row -> {
Arrays.stream(row)
.forEach(element -> System.out.print(element + " "));
System.out.println();
});
}
}
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!