Friday, September 15, 2023

How to transpose a matrix in Java? Example Tutorial

Hello guys, continuing the tradition of this week, where I have mostly published articles about coding exercises for Java beginners, today also I am going to share an interesting coding problem, many of you have solved in your college or school days. Yes, it's about writing a Java program to transpose a matrix. In the last couple of tutorials, we have learned how to add and subtract two matrices in Java (see here) and how to multiply two matrices in Java (see here). In this tutorial, I'll show you how to transpose a matrix in Java. 

The transpose of a matrix is a new matrix whose rows are the columns of the original. This means when you transpose a matrix the columns of the new matrix become the rows of the original matrix and vice-versa. In short, to transpose a matrix, just swap the rows and columns of the matrix. 

For example, if you have a matrix with 2 rows and 3 columns then transpose of that matrix will contain 3 rows and two columns.

Here is a matrix and its transpose, you can see that the original matrix is a 2x3 matrix i.e. 2 rows and 3 columns, while the transpose of the matrix is a 3x2 matrix i.e. 3 columns and 2 rows.  The superscript "T" means "transpose)



You can see it's pretty easy to transpose a matrix in mathematics but how easy it is to write a program to do this automatically for you? Well, we'll find in the next  paragraph.



Java Program to transpose a Matrix -Example

Here is our complete Java program to transpose a given Matrix. The program can handle both square and non-square matrices. A square matrix is a matrix. where rows and columns are equal, for example, a 2x2 or 3x3 matrix while a non-square matrix is a matrix where rows and columns are not the same e.g. 2x3 matrix or 1x3 matrix.

The program uses our object-oriented model which we have used in our earlier program about matrix multiplication. We have a Matrix class to represent a matrix, it contains both rows and columns as well it holds all the numbers inside a two-dimensional array. The class also contains methods to read, transpose and print matrix into the console.

Program for transposing a Matrix in Java


The read() method reads a matrix from the command line using the Scanner class. Since you cannot read an array directly, it asks the user to enter a number of rows and columns and then individual numbers. Once the user entered all data it creates the matrix and calls the transpose.  

This method transposes the matrix by swapping rows with columns. It doesn't create a new Matrix but transposes the original matrix, hence when you print the matrix before and after calling the transpose method, you will see the original as well the transpose of the matrix in the console.

Btw, if you love to solve programming problems and looking for some more programs to build and improve your coding skill, I suggest you solve programming exercises from interviews given on the Cracking the Coding Interview book

This book contains more than 189 problems from different areas of programming like an array, string, linked list etc. Solving those problems will give you very good practice.




Program for transposing a Matrix in Java

import java.util.Scanner;

/*
 * Java Program to transpose a Matrix. When you transpose
 * a matrix rows are replaced by columns. For example,
 * The transpose of a matrix is a new matrix whose rows are 
 * the columns of the original.
 */
public class MatrixTransposeDemo {

  public static void main(String[] args) {

    System.out.println("Welcome to Java program to transpose a Matrix");
    Scanner scnr = new Scanner(System.in);

    System.out.println("Please enter details of matrix");
    System.out.print("Please Enter number of rows: ");
    int row1 = scnr.nextInt();
    System.out.print("Please Enter number of columns: ");
    int column1 = scnr.nextInt();
    System.out.println();
    System.out.println("Enter first matrix elements");
    Matrix first = new Matrix(row1, column1);
    first.read(scnr);

    System.out.println("original matrix: ");
    first.print();

    // let's transpose the matrix now
    first.transpose();

    System.out.println("transpose of the matrix is ");
    first.print();
    scnr.close();

  }

}

/*
 * Java class to represent a Matrix. It uses a two dimensional array to
 * represent a Matrix.
 */
class Matrix {
  private int rows;
  private int columns;
  private int[][] data;

  public Matrix(int row, int column) {
    this.rows = row;
    this.columns = column;
    data = new int[rows][columns];
  }

  public Matrix(int[][] data) {
    this.data = data;
    this.rows = data.length;
    this.columns = data[0].length;
  }

  public int getRows() {
    return rows;
  }

  public int getColumns() {
    return columns;
  }

  /**
   * fills matrix from data entered by user in console
   * 
   * @param rows
   * @param columns
   */
  public void read(Scanner s) {    
    for (int i = 0; i < rows; i++) {
      for (int j = 0; j < columns; j++) {
        data[i][j] = s.nextInt();
      }
    }

  }

  /**
   * This method will transpose this matrix
   * 
   * @return
   */
  public void transpose() {
    int[][] temp = new int[columns][rows];
    for (int i = 0; i < rows; i++) {
      for (int j = 0; j < columns; j++) {
        temp[j][i] = data[i][j];
      }
    }
    data = temp;
  }

  /**
   * 
   * @param matrix
   */
  public void print() {
    for (int i = 0; i < rows; i++) {
      for (int j = 0; j < columns; j++) {
        System.out.print(data[i][j] + " ");
      }
      System.out.println();
    }
  }

}

Output
Welcome to Java program to transpose a Matrix
Please enter details of matrix
Please Enter number of rows: 2
Please Enter number of columns: 2

Enter first matrix elements
1
2
3
4
original matrix: 
1 2 
3 4 
transpose of the matrix is 
1 3 
2 4 


That's all about how to transpose a matrix in Java. It's one of the interesting coding problems for Java beginners. Some of you might argue the benefit of writing such programs but believe me, this is where the fundamentals are built. 

Even though I have not written any unit test, I suggest you write unit tests for this program, just to check our transpose matrix works for all kinds of matrices like both square and non-square matrices. 

If you don't know how to write Junit test cases in Java then please refer to these best JUnit and TDD courses, to learn unit testing and Test Driven Development in Java. The unit tests are the single biggest work ethic that separates a professional developer from a non-professional developer.

If you build the habit of writing unit test earlier in your career, you will mostly write quality and robust code.


Other Java Coding Exercises for Beginners for Practice
  • How to count vowels and consonants in a given String in Java? (solution)
  • How to implement binary search using recursion in Java? (solution)
  • How to calculate the square root of a given number in Java? (solution)
  • How to find the highest occurring word from a given file in Java? (solution)
  • How to check if the given String is palindrome or not in Java? (solution)
  • How to check if two rectangles intersect with each other in Java? (solution)
  • How to find all permutations of a given String in Java? (solution)
  • How to reverse a String in place in Java? (solution)
  • How to implement Linear Search in Java? (solution)
  • How to reverse words in a given String in Java? (solution)
  • How to check if two given Strings are Anagram in Java? (solution)
  • How to remove duplicate characters from String in Java? (solution)
  • How to check if a String contains duplicate characters in Java? (solution)
  • How to calculate the sum of all elements of an array in Java? (program)
  • How to reverse an array in place in Java? (solution)
  • How to find if given Integer is Palindrome in Java? (solution)
  • How to calculate the average of all numbers of an array in Java? (program)
Lastly, what is your favorite Java programming exercise? Palindrom, Prime Number, Fibonacci series, Binary Search, or this one?  Do let me know in comments. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.