What is a templated class matrix in Armadillo?
Overview
Armadillo is an open-source C++ library that aims to ease use and efficiency. Its high-level application programming interface is similar to Matlab; therefore, its operations are performed similarly.
Parameters
Armadillo provides a templated class matrix. The root matrix class is Mat<type>, where the <type> is one of the following:
floatdoublestd::complex<float>std::complex<double>shortintlong- Unsigned versions of
short,int, andlong
Syntax
The syntax of the Matrix is as follows:
class Matrix<type>
Here, <type> can be any of the data types given above.
Sample member functions
Some of the member functions and variables of the matrix class in Armadillo are as follows:
-
.n_rows: This shows the number of rows. -
.n_cols: This shows the number of columns. -
.n_elem: This shows the total number of elements. -
.is_empty(): This function tests if there are no elements. -
.begin(): This returns the iterator pointing to the first element. -
.end(): This returns the iterator pointing to the past-the-end element.
These are just some of the basic functions used for matrices in Armadillo.
Code
Let’s have a look at a sample matrix code in Armadillo.
// Library for RcppArmadillo#include <RcppArmadillo.h>// [[Rcpp::depends(RcppArmadillo)]]using namespace Rcpp;// [[Rcpp::export]]arma::mat mat_assign_A(arma::vec v, int rows, int cols, bool byrow = 0) {if (!byrow) {arma::mat A(v.begin(), rows, cols);return(A);}}
Explanation
The above code creates a matrix in Rcpp using the Armadillo library. Let’s discuss the code written in main.cpp in detail:
- Line 2: We include the
RcppArmadillolibrary. - Line 3: We show that this code file depends
RcppArmadillo. - Line 5: We export
Rcppto the code file. - Line 6: We add the header for the function that takes four parameters.
- Line 7: The
ifcondition shows that this loop will execute only if the value ofbyrow, which is given as a parameter, is equal to0. - Line 8: We create a matrix with 2 rows and 3 columns in Rcpp using the Armadillo library. The member function
.begin()gives the iterator pointing at the first element. - Line 9: We return the created matrix.
Let’s now discuss the code written in the main.r code file:
- Line 1: We bind both the code files using
sourceCpp. - Line 2: We call the function and provide the appropriate parameters. We catch the return value in
A. - Line 3: We print the matrix which was returned by the function call in the above line of code.
Note: There are two files in our code. One is an
.rfile namedmain.rand the other is a.cppfile namedmain.cpp. The major part of the code is written in the.cpp file, while the.rfile calls the function. Both the files are mutually integrated with each other usingsourceCpp.
Free Resources