C++ Program to Find the Transpose of a Matrix

16/06/2024 0 By indiafreenotes

Finding the transpose of a matrix involves swapping its rows with its columns. In other words, the element at position (i, j) in the original matrix moves to position (j, i) in the transposed matrix.

Problem Statement

Given a matrix, compute its transpose. The transpose of a matrix is obtained by swapping rows with columns.

Approach

  1. Initialize a Transposed Matrix:

Create a new matrix to store the transposed values, which will have dimensions swapped compared to the original matrix.

  1. Swap Elements:

Iterate through each element of the original matrix, and assign it to the transposed matrix by swapping the row and column indices.

Example

For a 3×3 matrix:

Original Matrix:

1 2 3

4 5 6

7 8 9

Transposed Matrix:

1 4 7

2 5 8

3 6 9

C++ Code Implementation

Here is a C++ program to compute the transpose of a matrix:

#include <iostream>

#include <vector>

using namespace std;

// Function to compute the transpose of a matrix

vector<vector<int>> transposeMatrix(const vector<vector<int>>& matrix) {

    int rows = matrix.size();

    int cols = matrix[0].size();

    vector<vector<int>> transposedMatrix(cols, vector<int>(rows));

    for (int i = 0; i < rows; ++i) {

        for (int j = 0; j < cols; ++j) {

            transposedMatrix[j][i] = matrix[i][j];

        }

    }

    return transposedMatrix;

}

// Function to print a matrix

void printMatrix(const vector<vector<int>>& matrix) {

    for (const auto& row : matrix) {

        for (const auto& elem : row) {

            cout << elem << ” “;

        }

        cout << endl;

    }

}

int main() {

    // Initializing a 3×3 matrix

    vector<vector<int>> matrix = {

        {1, 2, 3},

        {4, 5, 6},

        {7, 8, 9}

    };

    cout << “Original Matrix:” << endl;

    printMatrix(matrix);

    // Computing the transpose of the matrix

    vector<vector<int>> transposedMatrix = transposeMatrix(matrix);

    cout << “Transposed Matrix:” << endl;

    printMatrix(transposedMatrix);

    return 0;

}

Explanation

  1. Function transposeMatrix:

  • Parameters:

Takes a 2D vector (matrix).

  • Initialization:

Creates a new matrix (transposedMatrix) with swapped dimensions (number of rows becomes number of columns and vice versa).

  • Element Swapping:

Iterates through each element of the original matrix and assigns it to the corresponding position in the transposed matrix by swapping the indices.

  • Return Value:

Returns the transposed matrix.

  1. Function printMatrix:

Prints the matrix in a formatted way for better visualization.

  1. Main Function:

  • Initializes a sample 3×3 matrix.
  • Prints the original matrix.
  • Calls the transposeMatrix function to compute the transpose.
  • Prints the transposed matrix.