Matrix transpose using Armadillo in C++

Fellow coders, in this tutorial we are going to learn about matrix transpose using a high-quality linear algebra library in C++ called ‘armadillo’. Before we move on with our program, let us learn about matrix transpose in linear algebra.

What is matrix transpose?

Matrix transpose is an easy concept in linear algebra. We simply flip the original matrix and call it the transpose of the matrix. We can do so by switching the rows of the matrix with its columns. Therefore a 2×3 matrix becomes a 3×2 matrix after matrix transpose. Now let us learn about the library that we will use to perform this task.

What is Armadillo in C++?

As mentioned above, Armadillo is a linear library in the C++ programming language. It is straightforward and easy to use. This library provides efficient and streamlined base calculations. We can easily perform several tasks of linear algebra using the Armadillo library. It has a variety of functions to perform different mathematical operations.

Working with the code:

We are going to use the “trans()” function in the code below to calculate the transpose of the matrix.

#include <iostream>
#include <armadillo>
using namespace std;
using namespace arma;

int main()
{
       
    //let us create a random matrix with 5 rows and coloums
    mat A = randu<mat>(5,5);

    //calculating transpose of matrix A
    mat B = trans(A);

    //printing the matrix A
    cout << "Matrix A::\n"<<endl;
    cout<< A << endl;

    //printing the transpose of matrix A
    cout << "Matrix B(Trans of matrix)::" << endl;
    cout<< B << endl;
    return 0;
}

We can also use the “.t()” function which doesn’t take any parameters.

mat B = A.t();

Output:

Matrix A::
0.7868   0.4049   0.2742   0.8571   0.2393

0.2505   0.2513   0.5610   0.4998   0.3201

0.7107   0.0227   0.1400   0.4194   0.9105

0.9467   0.5206   0.5439   0.7443   0.1648

0.0193   0.3447   0.5219   0.2492   0.2455

 

Matrix B(Trans of matrix)::
0.7868   0.2505   0.7107   0.9467   0.0193

0.4049   0.2513   0.0227   0.5206   0.3447

0.2742   0.5610   0.1400   0.5439   0.5219

0.8571   0.4998   0.4194   0.7443   0.2492

0.2393   0.3201   0.9105   0.1648   0.2455

Also read: Adjacency Matrix representation of graph in C++

Leave a Reply

Your email address will not be published. Required fields are marked *