📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
Transposing a matrix involves converting rows into columns and vice versa. This is a common operation in linear algebra and is used in various fields such as physics, computer graphics, and statistics. In this tutorial, we will write a Java program to find the transpose of a given matrix.
2. Program Steps
1. Define a class named MatrixTranspose.
2. Inside the main method, define a 2D array matrix representing the matrix to be transposed.
3. Define a 2D array transpose to store the transposed matrix.
4. Use nested for loops to transpose the matrix by swapping its row and column indices and store the result in transpose.
5. Print the original matrix and its transpose.
3. Code Program
public class MatrixTranspose { // Step 1: Define a class named MatrixTranspose
public static void main(String[] args) { // Main method
// Step 2: Define a 2D array matrix representing the matrix to be transposed
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Step 3: Define a 2D array transpose to store the transposed matrix
int rows = matrix.length;
int columns = matrix[0].length;
int[][] transpose = new int[columns][rows];
// Step 4: Use nested for loops to transpose the matrix
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
transpose[j][i] = matrix[i][j];
}
}
// Step 5: Print the original matrix and its transpose
System.out.println("Original Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Transposed Matrix:");
for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
}
}
Output:
Original Matrix: 1 2 3 4 5 6 7 8 9 Transposed Matrix: 1 4 7 2 5 8 3 6 9
4. Step By Step Explanation
Step 1: A class named MatrixTranspose is defined.
Step 2: A 2D array matrix representing the matrix to be transposed is defined inside the main method.
Step 3: A 2D array transpose is defined to store the result of the transposed matrix.
Step 4: Nested for loops are used to transpose the matrix by swapping its row and column indices and store the result in transpose.
Step 5: The program prints the original matrix and its transpose.
Comments
Post a Comment
Leave Comment