Open In App
Related Articles

Program to find transpose of a matrix

Improve Article
Improve
Save Article
Save
Like Article
Like

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

Example:

matrix-transpose

Approach: Follow the given steps to solve the problem:

  • Run a nested loop using two integer pointers i and j for 0 <= i < N and 0 <= j < M
  • Set B[i][j] equal to A[j][i]

Below is the implementation of the above approach:

C++




// C++ program to find
// transpose of a matrix
#include <bits/stdc++.h>
using namespace std;
#define N 4
  
// This function stores transpose
// of A[][] in B[][]
void transpose(int A[][N], int B[][N])
{
    int i, j;
    for (i = 0; i < N; i++)
        for (j = 0; j < N; j++)
            B[i][j] = A[j][i];
}
  
// Driver code
int main()
{
    int A[N][N] = { { 1, 1, 1, 1 },
                    { 2, 2, 2, 2 },
                    { 3, 3, 3, 3 },
                    { 4, 4, 4, 4 } };
  
    // Note dimensions of B[][]
    int B[N][N], i, j;
  
      // Function call
    transpose(A, B);
  
    cout << "Result matrix is \n";
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++)
            cout << " " << B[i][j];
  
        cout << "\n";
    }
    return 0;
}
  
// This code is contributed by shivanisinghss2110


C




// C program to find
// transpose of a matrix
  
#include <stdio.h>
#define N 4
  
// This function stores transpose of A[][] in B[][]
void transpose(int A[][N], int B[][N])
{
    int i, j;
    for (i = 0; i < N; i++)
        for (j = 0; j < N; j++)
            B[i][j] = A[j][i];
}
  
// Driver code
int main()
{
    int A[N][N] = { { 1, 1, 1, 1 },
                    { 2, 2, 2, 2 },
                    { 3, 3, 3, 3 },
                    { 4, 4, 4, 4 } };
  
    // Note dimensions of B[][]
    int B[N][N], i, j;
  
      // Function call
    transpose(A, B);
  
    printf("Result matrix is \n");
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++)
            printf("%d ", B[i][j]);
        printf("\n");
    }
  
    return 0;
}


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;
  
          // Function call
        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.


Python3




# Python3 Program to find
# transpose of a matrix
  
N = 4
  
# This function stores
# transpose of A[][] in B[][]
  
  
def transpose(A, B):
  
    for i in range(N):
        for j in range(N):
            B[i][j] = A[j][i]
  
  
# Driver code
if __name__ == '__main__':
  A = [[1, 1, 1, 1],
       [2, 2, 2, 2],
       [3, 3, 3, 3],
       [4, 4, 4, 4]]
  
  
  # To store result
  B = [[0 for x in range(N)] for y in range(N)]
  
  # Function call
  transpose(A, B)
  
  print("Result matrix is")
  for i in range(N):
      for j in range(N):
          print(B[i][j], " ", end='')
      print()


C#




// C# Program to find
// transpose of a matrix
using System;
class GFG {
  
    static 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()
    {
        int[, ] A = { { 1, 1, 1, 1 },
                      { 2, 2, 2, 2 },
                      { 3, 3, 3, 3 },
                      { 4, 4, 4, 4 } };
  
        int[, ] B = new int[N, N];
  
          // Function call
        transpose(A, B);
  
        Console.WriteLine("Result matrix is \n");
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++)
                Console.Write(B[i, j] + " ");
            Console.Write("\n");
        }
    }
}
  
// This code is contributed by nitin mittal


Javascript




<script>
// javascript Program to find 
// transpose of a matrix    
  
     var N = 4;
  
    // This function stores transpose
    // of A in B
    function transpose(A , B) {
        var i, j;
        for (i = 0; i < N; i++)
            for (j = 0; j < N; j++)
                B[i][j] = A[j][i];
    }
  
    // Driver code
      
        var A = [ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ], [ 3, 3, 3, 3 ], [4, 4, 4, 4]];
  
        var B = Array(N);
        for(i=0;i<N;i++)
        B[i] =Array(N).fill(0);
  
        transpose(A, B);
  
        document.write("Result matrix is <br/>");
        for (i = 0; i < N; i++) {
            for (j = 0; j < N; j++)
                document.write(B[i][j] + " ");
            document.write("<br/>");
        }
// This code contributed by Rajput-Ji
</script>


PHP




<?php
  
// This function stores transpose
// of A[][] in B[][]
function transpose(&$A, &$B)
{
    $N = 4;
    for ($i = 0; $i < $N; $i++)
        for ($j = 0; $j < $N; $j++)
            $B[$i][$j] = $A[$j][$i];
}
  
// Driver code
  
$A = array(array(1, 1, 1, 1),
           array(2, 2, 2, 2),
           array(3, 3, 3, 3),
           array(4, 4, 4, 4));
  
$N = 4;
  
// Function call
transpose($A, $B);
  
echo "Result matrix is \n";
for ($i = 0; $i < $N; $i++)
{
    for ($j = 0; $j < $N; $j++)
    {
    echo $B[$i][$j];
    echo " ";
    }
    echo "\n";
}
  
// This code is contributed
// by Shivi_Aggarwal 
?>


Output

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

Time complexity: O(M x N).
Auxiliary Space: O(M x N), since M x N extra space has been used.

Program to find the transpose of a matrix using constant space:

NoteThis approach works only for square matrices (i.e., – where no. of rows are equal to the number of columns). This algorithm is also known as an “in-place” algorithm as it uses no extra space to solve the problem.

Follow the given steps to solve the problem:

  • Run a nested loop using two integer pointers i and j for 0 <= i < N and i+1 <= j < N
  • Swap A[i][j] with A[j][i]

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
  
#define N 4
  
// Converts A[][] to its transpose
void transpose(int A[][N])
{
    for (int i = 0; i < N; i++)
        for (int j = i + 1; j < N; j++)
            swap(A[i][j], A[j][i]);
}
  
int main()
{
    int A[N][N] = { { 1, 1, 1, 1 },
                    { 2, 2, 2, 2 },
                    { 3, 3, 3, 3 },
                    { 4, 4, 4, 4 } };
  
    transpose(A);
  
    printf("Modified matrix is \n");
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++)
            printf("%d ", A[i][j]);
        printf("\n");
    }
  
    return 0;
}


Java




// Java Program to find
// transpose of a matrix
  
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;
            }
    }
  
    // 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 } };
  
        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");
        }
    }
}


Python3




# Python3 Program to find
# transpose of a matrix
  
N = 4
  
# Finds transpose of A[][] in-place
  
  
def transpose(A):
  
    for i in range(N):
        for j in range(i+1, N):
            A[i][j], A[j][i] = A[j][i], A[i][j]
  
  
# driver code
A = [[1, 1, 1, 1],
     [2, 2, 2, 2],
     [3, 3, 3, 3],
     [4, 4, 4, 4]]
  
transpose(A)
  
print("Modified matrix is")
for i in range(N):
    for j in range(N):
        print(A[i][j], " ", end='')
    print()
  
# This code is contributed
# by Anant Agarwal.


C#




// C# Program to find transpose of
// a matrix
using System;
  
class GFG {
  
    static 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;
            }
    }
  
    // Driver code
    public static void Main()
    {
        int[, ] A = { { 1, 1, 1, 1 },
                      { 2, 2, 2, 2 },
                      { 3, 3, 3, 3 },
                      { 4, 4, 4, 4 } };
  
        transpose(A);
  
        Console.WriteLine("Modified matrix is ");
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++)
                Console.Write(A[i, j] + " ");
  
            Console.WriteLine();
        }
    }
}
  
// This code is contributed by anuj_67.


Javascript




<script>
  
// JavaScript Program to find 
// transpose of a matrix    
var N = 4;
  
    // Finds transpose of A in-place
    function transpose(A) {
        for (i = 0; i < N; i++)
            for (j = i + 1; j < N; j++) {
                var temp = A[i][j];
                A[i][j] = A[j][i];
                A[j][i] = temp;
            }
    }
  
    // Driver code
      
        var A = [ [ 1, 1, 1, 1 ], 
                  [ 2, 2, 2, 2 ],
                  [ 3, 3, 3, 3 ], 
                  [ 4, 4, 4, 4 ] ];
  
        transpose(A);
  
        document.write("Modified matrix is <br/>");
        for (i = 0; i < N; i++) {
            for (j = 0; j < N; j++)
                document.write(A[i][j] + " ");
            document.write("\<br/>");
        }
  
// This code is contributed by aashish1995
  
</script>


PHP




<?php
// Converts A[][] to its transpose
function transpose(&$A)
{
    $N = 4;
    for ($i = 0; $i < $N; $i++)
        for ($j = $i + 1; $j < $N; $j++)
            {
                $temp = $A[$i][$j];
                $A[$i][$j] = $A[$j][$i];
                $A[$j][$i] = $temp;
            }
}
  
// Driver Code
$N = 4;
$A = array(array(1, 1, 1, 1),
            array(2, 2, 2, 2),
           array(3, 3, 3, 3),
           array(4, 4, 4, 4));
  
transpose($A);
  
echo "Modified matrix is " . "\n";
for ($i = 0; $i < $N; $i++)
{
    for ($j = 0; $j < $N; $j++)
        echo $A[$i][$j] . " ";
    echo "\n";
}
  
// This code is contributed
// by Akanksha Rai(Abby_akku)
?>


Output

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

Time complexity: O(N2).
Auxiliary Space: O(1)


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 12 Oct, 2023
Like Article
Save Article
Similar Reads
Related Tutorials