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.
Armadillo provides a templated class matrix. The root matrix class is Mat<type>
, where the <type>
is one of the following:
float
double
std::complex<float>
std::complex<double>
short
int
long
short
, int
, and long
The syntax of the Matrix
is as follows:
class Matrix<type>
Here, <type>
can be any of the data types given above.
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.
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); } }
The above code creates a matrix in Rcpp
using the Armadillo library. Let’s discuss the code written in main.cpp
in detail:
RcppArmadillo
library.RcppArmadillo
.Rcpp
to the code file.if
condition shows that this loop will execute only if the value of byrow
, which is given as a parameter, is equal to 0
..begin()
gives the iterator pointing at the first element.Let’s now discuss the code written in the main.r
code file:
sourceCpp
.A
.Note: There are two files in our code. One is an
.r
file namedmain.r
and the other is a.cpp
file namedmain.cpp
. The major part of the code is written in the.cpp file
, while the.r
file calls the function. Both the files are mutually integrated with each other usingsourceCpp
.
RELATED TAGS
View all Courses