Transpose of a Matrix in C++

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

A transpose matrix is nothing but a new matrix obtained by interchanging rows of the original matrix with the columns of the original matrix.

In other words, we can say that the transpose matrix is obtained by flipping the matrix along the diagonal.

If a matrix initially of dimensions N×MN\times M, then after the transposition, the dimensions would be M×NM\times N. Please refer to the image below to visualize a matrix's transposition.

C++ Transpose of a matrix

Example-

Let the matrix (say MM) be

123
456
789
101112

Now M transpose of MTM^T will look like this -

14710
25811
36912

You can notice that all the rows of MTM^T are columns of MM, and columns of MTM^T are rows of MM. Also, it can be seen that the dimensions of MTM^T will be inverse to that of MM.

For example, if the dimension of MM is x×yx\times y, then the dimension of MTM^T will be y×xy\times x.

Approach

The approach to find the transpose of a matrix in C++ is very easy; the steps needed to be followed are listed below -

  • Let the given matrix be mat of dimension N×MN\times M.
  • Declare a 2-dimensional array say T_mat of dimension M×NM\times N.
  • Iterate from i=0i=0 to N1N-1 and do the following -
    • Iterate from j=0j=0 to M1M-1 and perform - T_matj,i=mati,jT\_mat_{j, i} = mat_{i, j}
  • Print the obtained transposed matrix.

Pseudocode

Code Implementation

Program to Find Transpose of a Matrix in C++ Using Constant Space

To find the transpose of a matrix in C++ using constant space, you can follow a simple approach: swapping elements in-place without using any additional memory for a temporary matrix. Here's the code implementation:

Code Implementation:

Output:

Here's an example of the program's output:

Complexity:

The time complexity of this program is O(N^2), where N is the size of the square matrix. The space complexity is constant, O(1), because it uses only a few extra integer variables to perform the transpose operation in place.

Conclusion

  • A matrix is a rectangular array of the same data types arranged in rows and columns.
  • The transpose of a matrix is a matrix obtained by interchanging rows with columns. It is usually denoted by MM^{'} or MTM^T
  • If the dimension of the initial matrix was N×MN\times M, then the dimension of the transposed matrix will be M×NM\times N.
  • Transpose of a matrix in C++ can be easily computed using nested loops.

Also Read