The Wayback Machine - https://web.archive.org/web/20240930152718/https://www.geeksforgeeks.org/java-transpose-matrix/
Open In App

Java Program to Find Transpose of Matrix

Last Updated : 31 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, the transpose of A[][] is obtained by changing A[i][j] to A[j][i].

Transpose of a matrix

Find Transpose of a Matrix in Java

There are two shapes in Matrix to find transpose as mentioned below:

  • Square Matrix
  • Rectangle Matrix

1. Transpose of Square Matrix

The below program finds the transpose of A[][] and stores the result in B[][], we can change N for different dimensions. 

Below is the implementation of the above method:

Java




// Java Program to find
// transpose of a matrix
  
class GFG {
    static final int N = 4;
  
    // This function stores transpose
    // of A[][] in B[][]
    static void transpose(int A[][], int B[][])
    {
        int i, j;
        for (i = 0; i < N; i++)
            for (j = 0; j < N; j++)
                B[i][j] = A[j][i];
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int A[][] = { { 1, 1, 1, 1 },
                      { 2, 2, 2, 2 },
                      { 3, 3, 3, 3 },
                      { 4, 4, 4, 4 } };
  
        int B[][] = new int[N][N], i, j;
  
        transpose(A, B);
  
        System.out.print("Result matrix is \n");
        for (i = 0; i < N; i++) {
            for (j = 0; j < N; j++)
                System.out.print(B[i][j] + " ");
            System.out.print("\n");
        }
    }
}
  
// This code is contributed by Anant Agarwal.


Output

Result matrix is 
1 2 3 4 
1 2 3 4 
1 2 3 4 
1 2 3 4 

The complexity of the above method

Time Complexity: O(n2)
Auxiliary Space: O(n2)

2. Transpose of Rectangular Matrix

The below program finds the transpose of A[][] and stores the result in B[][]. 

Java




// Java Program to find
// transpose of a matrix
  
class GFG {
    static final int M = 3;
    static final int N = 4;
  
    // This function stores transpose
    // of A[][] in B[][]
    static void transpose(int A[][], int B[][])
    {
        int i, j;
        for (i = 0; i < N; i++)
            for (j = 0; j < M; j++)
                B[i][j] = A[j][i];
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int A[][] = { { 1, 1, 1, 1 },
                      { 2, 2, 2, 2 },
                      { 3, 3, 3, 3 } };
  
        int B[][] = new int[N][M], i, j;
  
        transpose(A, B);
  
        System.out.print("Result matrix is \n");
        for (i = 0; i < N; i++) {
            for (j = 0; j < M; j++)
                System.out.print(B[i][j] + " ");
            System.out.print("\n");
        }
    }
}
  
// This code is contributed by Anant Agarwal.


Output

Result matrix is 
1 2 3 
1 2 3 
1 2 3 
1 2 3 

The complexity of the above method:

Time Complexity: O(n*m)
Auxiliary Space: O(n*m)

3. Transpose of In-Place for Square Matrix

Below is the implementation of the above topic:

Java




// Java Program to find
// transpose of a matrix
  
// Driver Class
class GFG {
    static final int N = 4;
  
    // Finds transpose of A[][] in-place
    static void transpose(int A[][])
    {
        for (int i = 0; i < N; i++)
            for (int j = i + 1; j < N; j++) {
                int temp = A[i][j];
                A[i][j] = A[j][i];
                A[j][i] = temp;
            }
    }
  
    // main function
    public static void main(String[] args)
    {
        int A[][] = { { 1, 1, 1, 1 },
                      { 2, 2, 2, 2 },
                      { 3, 3, 3, 3 },
                      { 4, 4, 4, 4 } };
  
        transpose(A);
  
        System.out.print("Modified matrix is \n");
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++)
                System.out.print(A[i][j] + " ");
            System.out.print("\n");
        }
    }
}


Output

Modified matrix is 
1 2 3 4 
1 2 3 4 
1 2 3 4 
1 2 3 4 

The complexity of the above method

Time Complexity: O(n2)
Auxiliary Space: O(1)

Please refer complete article on Program to find transpose of a matrix for more details!



Previous Article
Next Article

Similar Reads

Java Program to Display Transpose Matrix
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]. Approach: Create a 2-D Array.Insert the values in the array by running two nested loops. The outer ith loop will go till the no.of rows and the inner jth loop will run till the number of c
2 min read
Java Program to Determine if a given Matrix is a Sparse Matrix
A matrix is a collection of data elements arranged in a two-dimensional array-like structure, consisting of rows and columns. A matrix with a lot of zero values is called a sparse matrix. The program aims to count the number of zero values present in the matrix. If the number of zero values is more than half of the total number of elements in the m
3 min read
Java Program to Check Whether a Given Matrix is Lower Triangular Matrix or Not
In the lower triangular matrix, the elements that are present above the diagonal should be 0. Given a matrix and the task is to check the matrix is in lower triangular form or not. A matrix must be a square matrix. A square matrix is called lower triangular if all the entries above the main diagonal are zero. Example - Input: 1 0 0 1 2 0 1 2 3 Outp
2 min read
Java Program to Find the Frequency of Odd & Even Numbers in the Matrix
Matrix is simply a two-dimensional array. Just like in one-dimensional traversal operation is required to figure out. The task is to find the frequencies of odd and even number in the given matrix. The size of matrix is defined as product of numbers of columns and rows. So, the size of the matrix is m × n Here in the matrix M = number of rows in th
3 min read
Java Program to Find Laplacian Matrix of an Undirected Graph
The Laplacian matrix, also called the graph Laplacian, admittance matrix, Kirchhoff matrix or discrete Laplacian, is a matrix representation of a graph. To find the Laplacian matrix first, find adjacency matrix and degree matrix of a graph as the formula for the Laplacian matrix is as follows: Laplacian matrix = Degree matrix - Adjacency matrix Exa
4 min read
Java Program to Find the Normal and Trace of a Matrix
For a given 2D matrix, the purpose is to find the Trace and Normal of the matrix. Normal of a matrix is defined as the square root of the sum of squares of all the elements of the matrix. Trace of a given square matrix is defined as the sum of all the elements in the diagonal. Examples : Input : matrix[][] = {{1, 4, 4}, {2, 3, 7}, {0, 5, 1}}; Outpu
2 min read
Java Program to Find the Determinant of a Matrix
The Determinant of a Matrix is a real number that can be defined for square matrices only i.e, the number of rows and columns of the matrices must be equal. Moreover, it is helpful in determining the system of the linear equation as well as figuring the inverse of the stated matrix. Procedure to calculate: First, we need to calculate the cofactor o
5 min read
Java Program to Find the Maximum Element in a Matrix
Given a multi-dimensional 2D matrix of n rows and m column order N × M. The task is to find the maximum element in the given matrix. Illustration: Input : mat[][] = { {1,3,4,19}, {11,10,12,1}, {7,9,0,4,99} } Output : 99 Methods: Iterative method (naive approach)Using the principle of recursion (Bit more optimal approach) Method 1: Iterative method
3 min read
Java Program to Find maximum element of each row in a matrix
Given a matrix, the task is to find the maximum element of each row. Examples: Input : [1, 2, 3] [1, 4, 9] [76, 34, 21] Output : 3 9 76 Input : [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2] Output : 21 65 56 Approach : Approach is very simple. The idea is to run the loop for no_of_rows. Check each element inside the row and find for the maximum eleme
2 min read
Java Program to Find median in row wise sorted matrix
We are given a row-wise sorted matrix of size r*c, we need to find the median of the matrix given. It is assumed that r*c is always odd.Examples:  Input : 1 3 5 2 6 9 3 6 9 Output : Median is 5 If we put all the values in a sorted array A[] = 1 2 3 3 5 6 6 9 9) Input: 1 3 4 2 5 6 7 8 9 Output: Median is 5Recommended: Please solve it on “PRACTICE ”
4 min read
Java Program for Program to find area of a circle
Area of a circle can simply be evaluated using following formula. Area = pi * r2 where r is radius of circle Java Code // Java program to find area // of circle class Test { static final double PI = Math.PI; static double findArea(int r) { return PI * Math.pow(r, 2); } // Driver method public static void main(String[] args) { System.out.println(
1 min read
Java Program to Print Matrix in Z form
Given a square matrix of order n*n, we need to print elements of the matrix in Z form Examples: Input : mat[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : 1 2 3 5 7 8 9 Input : mat[][] = {5, 19, 8, 7, 4, 1, 14, 8, 2, 20, 1, 9, 1, 2, 55, 4} Output: 5 19 8 7 14 20 1 2 55 4 Java Code // Java program to print a // square matrix in Z form import java.lang.*
2 min read
Java Program to Interchange Any Two Rows in the Matrix
Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Rows in the given matrix. Swap Operation is required to interchange the elements of two rows. O(1) operation to swap two rows is impossible because complete traversal between two rows is required. Examples Input 1: K = 1, L = 2, mat[][] = {{2, 1, 4},
2 min read
Java Program for Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
3 min read
Java Program to Interchange Elements of First and Last in a Matrix Across Columns
For a given 4 x 4 matrix, the task is to interchange the elements of the first and last columns and then return the resultant matrix. Examples : Input 1 : 1 1 5 0 2 3 7 2 8 9 1 3 6 7 8 2 Output 1 : 0 1 5 1 2 3 7 2 3 9 1 8 2 7 8 6 Input 2 : 7 8 9 10 11 13 14 1 15 7 12 22 11 21 30 1 Output 2 : 10 8 9 7 1 13 14 11 22 7 12 15 1 21 30 11 Approach: To ge
3 min read
Java Program to Add Two Matrix Using Iterative Approach
Given two matrices A and B, Add two matrices using iterative approaches in Java, like for loop, while loop, do-while loop. For the addition of two matrices, the necessary condition is that both the matrices must have the same size, and addition must take complete iteration to both the matrices. Examples Input: A[][] = {{1, 3}, {2, 4}} B[][] = {{1,
2 min read
Java Program to Display Upper Triangular Matrix
Upper Triangular Matrix is a matrix in which all the elements below the principal matrix are 0. A necessary condition is that matrix must be Square matrix in nature. If the matrix is not a square matrix, it can never be called the upper triangular matrix. ExamplesInput 1: mat[][] = { {2, 1, 4}, {1, 2, 3}, {3, 6, 2} } Output : mat[][]= { {2, 1, 4},
2 min read
Java Program to Display Lower Triangular Matrix
Lower Triangular Matrix is a square matrix in which all the elements above the principal diagonal are 0. If the matrix is not a square matrix, it can never be called the lower triangular matrix. Examples Input 1: mat[][] = { {2, 1, 4}, {1, 2, 3}, {3, 6, 2}} Output : mat[][]= {{2, 0, 0}, {1, 2, 0}, {3, 6, 2}} Explanation : All the element below the
2 min read
Java Program to Interchange Any Two Columns in the Matrix
Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Columns(ie column no K and L given in the input) in the given matrix. Swap Operation is required to interchange the elements of two columns. O(1) operation to swap two columns is impossible because complete traversal between two columns is required. E
2 min read
Java Program to Accept a Matrix of Order M x N & Interchange the Diagonals
Problem Description: Write a Java program that accepts a matrix of M × N order and then interchange diagonals of the matrix. Steps: 1. We can only interchange diagonals for a square matrix. 2. Create a square matrix of size [M × M]. 3. Check the matrix is a square matrix or not. If the matrix is square then follow step 3 else terminate the program.
4 min read
Java Program to Represent Linear Equations in Matrix Form
Let's look at the System of Linear Equation with the help of an example: The input of coefficients and variables is taken into play for consideration. The scanner package should be imported into the program in order to use the object of the Scanner class to take the input from the user.The array will be initialized to store the variables of the equ
4 min read
Java Program to Check Whether a Matrix is Symmetric or Not
A symmetric matrix is a square matrix in which the transpose of the square matrix is the same as the original square matrix. A square matrix is a matrix in which the number of columns is the same as the number of rows. If the matrix is a symmetric matrix then it is also a square matrix but vice versa isn't true. Matrix is simply considered as 2D ar
4 min read
Java Program to Create a Matrix and Fill it with Prime Numbers
Prime Numbers are the number which can be divisible by only 1 and itself, it cannot be divisible by any other number. The task here is to find the prime numbers and store them in the form of a matrix. Example: Prime numbers are: 2, 3, 5, 7 Output: 2 3 5 7 Prime numbers : 2, 3, 5, 7, 9, 11, 13, 17, 19 Output: 2 3 5 7 9 11 13 17 19 Approach: First, t
3 min read
Java Program to Print Boundary Elements of the Matrix
Given a matrix of size Row x Col Print the boundary elements of the matrix. Boundary elements are those elements which are not surrounded by elements on all four directions, i.e. elements in the first row, first column, last row and last column. Example: Input : 1 2 3 4 5 6 7 8 9 Output: 1 2 3 4 6 7 8 9Approach: Take the matrix as input from the us
2 min read
Java Program to Interchange Elements of First and Last in a Matrix Across Rows
For a given 4 × 4 matrix, the task is to interchange the elements of the first and last rows and then return the resultant matrix. Illustration: Input 1: 1 1 5 0 2 3 7 2 8 9 1 3 6 7 8 2 Output 1: 6 7 8 2 2 3 7 2 8 9 1 3 1 1 5 0 Input 2: 7 8 9 10 11 13 14 1 15 7 12 22 11 21 30 1 Output 2: 11 21 30 1 11 13 14 1 15 7 12 22 7 8 9 10 Approach: To get th
3 min read
Java Program to Rotate Matrix Elements
Matrix is simply a two-dimensional array. So the goal is to deal with fixed indices at which elements are present and to perform operations on indexes such that elements on the addressed should be swapped in such a manner it should lookout as the matrix is rotated. Here we will be discussing two methods in dealing with indices Using naive approach
6 min read
Java Program to Compute the Sum of Diagonals of a Matrix
For a given 2D square matrix of size N*N, the task is to find the sum of elements in the Principal and Secondary diagonals. For example, analyze the following 4 × 4 input matrix. a00 a01 a02 a03a10 a11 a12 a13a20 a21 a22 a23a30 a31 a32 a33 Example: Input 1 : 6 7 3 4 8 9 2 1 1 2 9 6 6 5 7 2Output 1 : Principal Diagonal: 26 Secondary Diagonal: 14 Inp
4 min read
Java Program to Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction
Given a square matrix mat[][] of dimension N and an integer K, the task is to rotate the matrix by 90 degrees K times without changing the position of the diagonal elements. Examples: Input: mat[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}, K = 1Output: 1 16 11 6 5 22 7 12 9 2 23 18 13
4 min read
Java Program to Modify a matrix by rotating ith row exactly i times in clockwise direction
Given a matrix mat[][] of dimensions M * N, the task is to print the matrix obtained after rotating every ith row of the matrix i times in a clockwise direction. Examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output:1 2 36 4 58 9 7Explanation:The 0th row is rotated 0 times. Therefore, the 0th row remains the same as {1, 2, 3}.The 1st r
3 min read
Java Program to Maximize sum of diagonal of a matrix by rotating all rows or all columns
Given a square matrix, mat[][] of dimensions N * N, the task is find the maximum sum of diagonal elements possible from the given matrix by rotating either all the rows or all the columns of the matrix by a positive integer. Examples: Input: mat[][] = { { 1, 1, 2 }, { 2, 1, 2 }, { 1, 2, 2 } }Output: 6 Explanation: Rotating all the columns of matrix
3 min read
Article Tags :