How to find transpose of a 2D Matrix in C++
In this shot, we will go over how to find the transpose of a two-dimensional array (matrix).
What is the transpose of a matrix?
The transpose of a matrix is taken by switching the columns and rows of a matrix. Specifically, the matrix is flipped along its diagonal. The diagonal will remain the same.
Explanation of the code:
Since we are using a 2-D array, we need to use a nested for loop to traverse through it.
- First, initialize your 2-D array.
- Run a nested
forloop. The outerforloop will iterate through rows and the inner loop will iterate through columns. - While accessing element
arr[row][col], insert the element intotranspose[col][row], i.e., switch the rows and columns. For example,
arr[0][1]will be placed attranspose[1][0], so two and four will swap positions in the transpose matrix. - The
forloop will iterate through every element and insert it into the correct index in thetranspose2-D array.
#include<iostream>using namespace std;// user defined function to print 2 day array with correct formatvoid printArr (int arr[][3], int columns){for(int i = 0; i < 3; i++){for(int j = 0; j < columns; j++){cout << arr[i][j] << " ";}cout << endl;}}int main(){// declare matrixconst int rows = 3;const int columns = 3;int arr[rows][columns] = {1, 2, 3,4, 5, 6,7, 8, 9};// declare transpose matrix of same sizeint transpose[rows][columns];cout << "Original Matrix: " << endl;printArr(arr, columns);// outer for loop to traverse rowsfor(int i = 0; i < rows; i++){// inner for loop to traverse columnfor(int j = 0; j < columns; j++){// insert arr[row][col] to transpose[col][row]transpose[j][i] = arr[i][j];}}cout<< "Transpose Matrix: " << endl;printArr(transpose, columns);return 0;}