Armadillo_ C++ Library for Linear Algebra & Scientific Computing - API Documentation
Armadillo_ C++ Library for Linear Algebra & Scientific Computing - API Documentation
Armadillo
C++ library for linear algebra & scientific computing
Preamble
For converting Matlab/Octave programs, see the Please cite the following papers if you use Armadillo in your
syntax conversion table research and/or software.
Citations are useful for the continued development and
First time users: please see the short example maintenance of the library.
program
Conrad Sanderson and Ryan Curtin.
If you discover any bugs or regressions, please report Armadillo: a template-based C++ library for linear algebra.
them Journal of Open Source Software, Vol. 1, pp. 26, 2016.
Overview
arma.sourceforge.net/docs.html 1/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.set_size change size without keeping elements (fast)
.reshape change size while keeping elements
.resize change size while keeping elements and preserving layout
.copy_size change size to be same as given object
.reset change size to empty
iterators (matrices) iterators and associated member functions for dense matrices and vectors
iterators (cubes) iterators and associated member functions for cubes
iterators (sparse matrices) iterators and associated member functions for sparse matrices
iterators (submatrices) iterators and associated member functions for submatrices & subcubes
compat. container functions compatibility container functions
.save/.load (matrices & cubes) save/load matrices and cubes in files or streams
.save/.load (fields) save/load fields in files or streams
Generated Vectors/Matrices/Cubes
arma.sourceforge.net/docs.html 2/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
spones generate sparse matrix with non-zero elements set to one
sprandu / sprandn generate sparse matrix with non-zero elements set to random values
toeplitz generate Toeplitz matrix
Functions of Vectors/Matrices/Cubes
arma.sourceforge.net/docs.html 3/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
trimatu_ind / trimatl_ind obtain indices of upper/lower triangular part
unique return unique elements
vectorise flatten matrix into vector
misc functions miscellaneous element-wise functions: exp, log, pow, sqrt, round, sign, ...
trig functions trigonometric element-wise functions: cos, sin, ...
eigs_sym limited number of eigenvalues & eigenvectors of sparse symmetric real matrix
eigs_gen limited number of eigenvalues & eigenvectors of sparse general square matrix
spsolve solve sparse systems of linear equations
svds truncated svd: limited number of singular values & singular vectors of sparse matrix
conv 1D convolution
conv2 2D convolution
fft / ifft 1D fast Fourier transform and its inverse
fft2 / ifft2 2D fast Fourier transform and its inverse
interp1 1D interpolation
interp2 2D interpolation
polyfit find polynomial coefficients for data fitting
polyval evaluate polynomial
Miscellaneous
arma.sourceforge.net/docs.html 5/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
arma.sourceforge.net/docs.html 6/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Mat<type>
mat
cx_mat
Classes for dense matrices, with elements stored in column-major ordering (ie. column by column)
In this documentation the mat type is used for convenience; it is possible to use other types instead, eg. fmat
Functions which use LAPACK (generally matrix decompositions) are only valid for the following types: mat, dmat, fmat,
cx_mat, cx_dmat, cx_fmat
Constructors:
mat()
mat(n_rows, n_cols)
mat(n_rows, n_cols, fill_form) (elements are initialised according to fill_form)
mat(size(X))
mat(size(X), fill_form) (elements are initialised according to fill_form)
mat(mat)
mat(vec)
mat(rowvec)
mat(initializer_list)
mat(string)
mat(std::vector) (treated as a column vector)
mat(sp_mat) (for converting a sparse matrix to a dense matrix)
cx_mat(mat,mat) (for constructing a complex matrix out of two real matrices)
The elements can be explicitly initialised during construction by specifying fill_form, which is one of:
fill::zeros ↦ set all elements to 0
fill::ones ↦ set all elements to 1
fill::eye ↦ set the elements on the main diagonal to 1 and off-diagonal elements to 0
fill::randu ↦ set all elements to random values from a uniform distribution in the [0,1] interval
set all elements to random values from a normal/Gaussian distribution with zero mean and unit
fill::randn ↦
variance
fill::value(scalar) ↦ set all elements to specified scalar (Armadillo 10.6 and later)
fill::none ↦ do not initialise the elements
Caveat:
in Armadillo 10.4 and earlier versions, the elements are not initialised during construction unless fill_form is specified
(ie. without specifying fill_form, the elements may contain garbage values, including NaN)
in Armadillo 10.5 and later versions, by default the elements are initialised to zero during construction
For the mat(string) constructor, the format is elements separated by spaces, and rows denoted by semicolons; for example,
the 2x2 identity matrix can be created using "1 0; 0 1".
Caveat: string based initialisation is slower than directly setting the elements or using element initialisation.
Each instance of mat automatically allocates and releases internal memory. All internally allocated memory used by an
instance of mat is automatically released as soon as the instance goes out of scope. For example, if an instance of mat is
declared inside a function, it will be automatically destroyed at the end of the function. To forcefully release memory at any
point, use .reset(); note that in normal use this is not required.
Advanced constructors:
Create a matrix using data from writable auxiliary (external) memory, where ptr_aux_mem is a pointer to the
memory. By default the matrix allocates its own memory and copies data from the auxiliary memory (for safety).
However, if copy_aux_mem is set to false, the matrix will instead directly use the auxiliary memory (ie. no
copying); this is faster, but can be dangerous unless you know what you are doing!
The strict parameter comes into effect only when copy_aux_mem is set to false (ie. the matrix is directly using
auxiliary memory)
when strict is set to false, the matrix will use the auxiliary memory until a size change or an aliasing event
when strict is set to true, the matrix will be bound to the auxiliary memory for its lifetime; the number of
elements in the matrix can't be changed
arma.sourceforge.net/docs.html 7/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Create a matrix by copying data from read-only auxiliary memory, where ptr_aux_mem is a pointer to the memory
mat::fixed<n_rows, n_cols>
Create a fixed size matrix, with the size specified via template arguments. Memory for the matrix is reserved at
compile time. This is generally faster than dynamic memory allocation, but the size of the matrix can't be changed
afterwards (directly or indirectly).
For convenience, there are several pre-defined typedefs for each matrix type (where the types are: umat, imat,
fmat, mat, cx_fmat, cx_mat). The typedefs specify a square matrix size, ranging from 2x2 to 9x9. The typedefs
were defined by appending a two digit form of the size to the matrix type; examples: mat33 is equivalent to
mat::fixed<3,3>, while cx_mat44 is equivalent to cx_mat::fixed<4,4>.
Create a fixed size matrix, with the size specified via template arguments; data is copied from auxiliary memory,
where ptr_aux_mem is a pointer to the memory
Examples:
mat A(5, 5, fill::randu);
double x = A(1,2);
mat B = A + A;
mat C = A * B;
mat D = A % B;
cx_mat X(A,B);
B.zeros();
B.set_size(10,10);
B.ones(5,6);
B.print("B:");
mat::fixed<5,6> F;
double aux_mem[24];
mat H(&aux_mem[0], 4, 6, false); // use auxiliary memory
Caveat: For mathematical correctness, scalars are treated as 1x1 matrices during initialisation. As such, the code below will
not generate a 5x5 matrix with every element equal to 123.0:
mat A(5,5); A = 123.0;
or
mat A(5,5,fill::none); A.fill(123.0); // Armadillo 10.5 and earlier
See also:
matrix attributes
accessing elements
initialising elements
math & relational operators
submatrix views
saving & loading matrices
printing matrices
element iterators
.eval()
conv_to() (convert between matrix types)
explanation of typedef (cplusplus.com)
Col class
Row class
Cube class
SpMat class (sparse matrix with compressed sparse column format)
config.hpp
arma.sourceforge.net/docs.html 8/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Col<type>
vec
cx_vec
The Col<type> class is derived from the Mat<type> class and inherits most of the member functions
In this documentation, the vec and colvec types have the same meaning and are used interchangeably
In this documentation, the types vec or colvec are used for convenience; it is possible to use other types instead, eg. fvec,
fcolvec
Functions which take Mat as input can generally also take Col as input; main exceptions are functions which require square
matrices
Constructors:
vec()
vec(n_elem)
vec(n_elem, fill_form) (elements are initialised according to fill_form)
vec(size(X))
vec(size(X), fill_form) (elements are initialised according to fill_form)
vec(vec)
vec(mat) (std::logic_error exception is thrown if the given matrix has more than one column)
vec(initializer_list)
vec(string) (elements separated by spaces)
vec(std::vector)
cx_vec(vec,vec) (for constructing a complex vector out of two real vectors)
Caveat:
in Armadillo 10.4 and earlier versions, the elements are not initialised during construction unless fill_form is specified,
as per the Mat class
(ie. without specifying fill_form, the elements may contain garbage values, including NaN)
in Armadillo 10.5 and later versions, by default the elements are initialised to zero during construction
Advanced constructors:
Create a column vector using data from writable auxiliary (external) memory, where ptr_aux_mem is a pointer to
the memory. By default the vector allocates its own memory and copies data from the auxiliary memory (for
safety). However, if copy_aux_mem is set to false, the vector will instead directly use the auxiliary memory (ie. no
copying); this is faster, but can be dangerous unless you know what you are doing!
The strict parameter comes into effect only when copy_aux_mem is set to false (ie. the vector is directly using
auxiliary memory)
when strict is set to false, the vector will use the auxiliary memory until a size change or an aliasing event
when strict is set to true, the vector will be bound to the auxiliary memory for its lifetime; the number of
elements in the vector can't be changed
Create a column vector by copying data from read-only auxiliary memory, where ptr_aux_mem is a pointer to the
memory
vec::fixed<number_of_elements>
Create a fixed size column vector, with the size specified via the template argument. Memory for the vector is
reserved at compile time. This is generally faster than dynamic memory allocation, but the size of the vector can't
be changed afterwards (directly or indirectly).
For convenience, there are several pre-defined typedefs for each vector type (where the types are: uvec, ivec,
fvec, vec, cx_fvec, cx_vec as well as the corresponding colvec versions). The pre-defined typedefs specify vector
sizes ranging from 2 to 9. The typedefs were defined by appending a single digit form of the size to the vector
type; examples: vec3 is equivalent to vec::fixed<3>, while cx_vec4 is equivalent to cx_vec::fixed<4>.
vec::fixed<number_of_elements>(const ptr_aux_mem)
arma.sourceforge.net/docs.html 9/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Create a fixed size column vector, with the size specified via the template argument; data is copied from auxiliary
memory, where ptr_aux_mem is a pointer to the memory
Examples:
vec x(10);
vec y(10, fill::zeros);
Caveat: For mathematical correctness, scalars are treated as 1x1 matrices during initialisation. As such, the code below will
not generate a column vector with every element equal to 123.0:
vec v(5); v = 123.0;
or
vec v(5, fill::none); v.fill(123.0); // Armadillo 10.5 and earlier
See also:
element initialisation
Mat class
Row class
arma.sourceforge.net/docs.html 10/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Row<type>
rowvec
cx_rowvec
The template Row<type> class is derived from the Mat<type> class and inherits most of the member functions
In this documentation, the rowvec type is used for convenience; it is possible to use other types instead, eg. frowvec
Functions which take Mat as input can generally also take Row as input. Main exceptions are functions which require square
matrices
Constructors:
rowvec()
rowvec(n_elem)
rowvec(n_elem, fill_form) (elements are initialised according to fill_form)
rowvec(size(X))
rowvec(size(X), fill_form) (elements are initialised according to fill_form)
rowvec(rowvec)
rowvec(mat) (std::logic_error exception is thrown if the given matrix has more than one row)
rowvec(initializer_list)
rowvec(string) (elements separated by spaces)
rowvec(std::vector)
cx_rowvec(rowvec,rowvec) (for constructing a complex row vector out of two real row vectors)
Caveat:
in Armadillo 10.4 and earlier versions, the elements are not initialised during construction unless fill_form is specified,
as per the Mat class
(ie. without specifying fill_form, the elements may contain garbage values, including NaN)
in Armadillo 10.5 and later versions, by default the elements are initialised to zero during construction
Advanced constructors:
Create a row vector using data from writable auxiliary (external) memory, where ptr_aux_mem is a pointer to the
memory. By default the vector allocates its own memory and copies data from the auxiliary memory (for safety).
However, if copy_aux_mem is set to false, the vector will instead directly use the auxiliary memory (ie. no
copying); this is faster, but can be dangerous unless you know what you are doing!
The strict parameter comes into effect only when copy_aux_mem is set to false (ie. the vector is directly using
auxiliary memory)
when strict is set to false, the vector will use the auxiliary memory until a size change or an aliasing event
when strict is set to true, the vector will be bound to the auxiliary memory for its lifetime; the number of
elements in the vector can't be changed
Create a row vector by copying data from read-only auxiliary memory, where ptr_aux_mem is a pointer to the
memory
rowvec::fixed<number_of_elements>
Create a fixed size row vector, with the size specified via the template argument. Memory for the vector is
reserved at compile time. This is generally faster than dynamic memory allocation, but the size of the vector can't
be changed afterwards (directly or indirectly).
For convenience, there are several pre-defined typedefs for each vector type (where the types are: urowvec,
irowvec, frowvec, rowvec, cx_frowvec, cx_rowvec). The pre-defined typedefs specify vector sizes ranging from 2 to
9. The typedefs were defined by appending a single digit form of the size to the vector type; examples: rowvec3 is
equivalent to rowvec::fixed<3>, while cx_rowvec4 is equivalent to cx_rowvec::fixed<4>.
rowvec::fixed<number_of_elements>(const ptr_aux_mem)
Create a fixed size row vector, with the size specified via the template argument; data is copied from auxiliary
memory, where ptr_aux_mem is a pointer to the memory
arma.sourceforge.net/docs.html 11/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Examples:
rowvec x(10);
rowvec y(10, fill::zeros);
Caveat: For mathematical correctness, scalars are treated as 1x1 matrices during initialisation. As such, the code below will
not generate a row vector with every element equal to 123.0:
rowvec r(5); r = 123.0;
or
rowvec r(5, fill::none); r.fill(123.0); // Armadillo 10.5 and earlier
See also:
element initialisation
Mat class
Col class
arma.sourceforge.net/docs.html 12/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Cube<type>
cube
cx_cube
Classes for cubes (quasi 3rd order tensors), also known as "3D matrices"
In this documentation the cube type is used for convenience; it is possible to use other types instead, eg. fcube
Cube data is stored as a set of slices (matrices) stored contiguously within memory. Within each slice, elements are stored
with column-major ordering (ie. column by column)
Each slice can be interpreted as a matrix, hence functions which take Mat as input can generally also take cube slices as input
Constructors:
cube()
cube(n_rows, n_cols, n_slices)
cube(n_rows, n_cols, n_slices, fill_form) (elements are initialised according to fill_form)
cube(size(X))
cube(size(X), fill_form) (elements are initialised according to fill_form)
cube(cube)
cx_cube(cube, cube) (for constructing a complex cube out of two real cubes)
Caveat:
in Armadillo 10.4 and earlier versions, the elements are not initialised during construction unless fill_form is specified,
as per the Mat class (except for fill::eye)
(ie. without specifying fill_form, the elements may contain garbage values, including NaN)
in Armadillo 10.5 and later versions, by default the elements are initialised to zero during construction
Each instance of cube automatically allocates and releases internal memory. All internally allocated memory used by an
instance of cube is automatically released as soon as the instance goes out of scope. For example, if an instance of cube is
declared inside a function, it will be automatically destroyed at the end of the function. To forcefully release memory at any
point, use .reset(); note that in normal use this is not required.
Advanced constructors:
Create a fixed size cube, with the size specified via template arguments. Memory for the cube is reserved at
compile time. This is generally faster than dynamic memory allocation, but the size of the cube can't be changed
afterwards (directly or indirectly).
Create a cube using data from writable auxiliary (external) memory, where ptr_aux_mem is a pointer to the
memory. By default the cube allocates its own memory and copies data from the auxiliary memory (for safety).
However, if copy_aux_mem is set to false, the cube will instead directly use the auxiliary memory (ie. no copying);
this is faster, but can be dangerous unless you know what you are doing!
The strict parameter comes into effect only when copy_aux_mem is set to false (ie. the cube is directly using
auxiliary memory)
when strict is set to false, the cube will use the auxiliary memory until a size change or an aliasing event
when strict is set to true, the cube will be bound to the auxiliary memory for its lifetime; the number of
elements in the cube can't be changed
Create a cube by copying data from read-only auxiliary memory, where ptr_aux_mem is a pointer to the memory
Examples:
cube x(1, 2, 3);
cube y(4, 5, 6, fill::randu);
arma.sourceforge.net/docs.html 13/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cube::fixed<4,5,6> f;
f.ones();
Caveats:
The size of individual slices can't be changed. For example, the following will not work:
cube c(5,6,7);
c.slice(0) = randu<mat>(10,20); // wrong size
For mathematical correctness, scalars are treated as 1x1x1 cubes during initialisation. As such, the code below will not
generate a cube with every element equal to 123.0:
cube c(5,6,7); c = 123.0;
or
cube c(5,6,7,fill::none); c.fill(123.0); // Armadillo 10.5 and earlier
See also:
cube attributes
accessing elements
math & relational operators
subcube views and slices
saving & loading cubes
element iterators
field class
Mat class
arma.sourceforge.net/docs.html 14/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
field<object_type>
Somewhat similar to a matrix or cube, but instead of each element being a scalar, each element can be a vector, or matrix, or
cube
Each element can have an arbitrary size (eg. in a field of matrices, each matrix can have a unique size)
Constructors, where object_type is another class, eg. vec, mat, std::string, etc:
field<object_type>()
field<object_type>(n_elem)
field<object_type>(n_rows, n_cols)
field<object_type>(n_rows, n_cols, n_slices)
field<object_type>(size(X))
field<object_type>(field<object_type>)
Caveat: to store a set of matrices of the same size, the Cube class is more efficient
Examples:
mat A = randn(2,3);
mat B = randn(4,5);
field<mat> F(2,1);
F(0,0) = A;
F(1,0) = B;
F.print("F:");
F.save("mat_field");
See also:
field attributes
subfield views
saving/loading fields
Cube class
arma.sourceforge.net/docs.html 15/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
SpMat<type>
sp_mat
sp_cx_mat
Classes for sparse matrices; intended for storing very large matrices, where the vast majority of elements is zero
The root sparse matrix class is SpMat<type>, where type is one of:
float, double, std::complex<float>, std::complex<double>, short, int, long and unsigned versions of short, int, long
In this documentation the sp_mat type is used for convenience; it is possible to use other types instead, eg. sp_fmat
Constructors:
sp_mat()
sp_mat(n_rows, n_cols)
sp_mat(size(X))
sp_mat(sp_mat)
sp_mat(mat) (for converting a dense matrix to a sparse matrix)
sp_cx_mat(sp_mat,sp_mat) (for constructing a complex matrix out of two real matrices)
All elements are treated as zero by default (ie. the matrix is initialised to contain zeros)
Non-zero elements are stored in compressed sparse column (CSC) format (ie. column-major ordering); zero-valued elements
are never stored
This class behaves in a similar manner to the Mat class; however, member functions which set all elements to non-zero values
(and hence do not make sense for sparse matrices) have been deliberately omitted; examples of omitted functions: .fill(),
.ones(), += scalar, etc.
For forms 1, 2, 3, locations is a dense matrix of type umat, with a size of 2 x N, where N is the number of values to
be inserted; the location of the i-th element is specified by the contents of the i-th column of the locations matrix,
where the row is in locations(0,i), and the column is in locations(1,i)
For form 4, rowind is a dense column vector of type uvec containing the row indices of the values to be inserted,
and colptr is a dense column vector of type uvec (with length n_cols + 1) containing indices of values corresponding
to the start of new columns; the vectors correspond to the arrays used by the compressed sparse column format;
this form is useful for copying data from other CSC sparse matrix containers
For all forms, values is a dense column vector containing the values to be inserted; it must have the same element
type as the sparse matrix. For forms 1 and 2, the value in values[i] will be inserted at the location specified by the
i-th column of the locations matrix.
For form 3, add_values is either true or false; when set to true, identical locations are allowed, and the values at
identical locations are added
The size of the constructed matrix is either automatically determined from the maximal locations in the locations
matrix (form 1), or manually specified via n_rows and n_cols (forms 2, 3, 4)
If sort_locations is set to false, the locations matrix is assumed to contain locations that are already sorted
according to column-major ordering; do not set this to false unless you know what you are doing!
If check_for_zeros is set to false, the values vector is assumed to contain no zero values; do not set this to false
unless you know what you are doing!
The following subset of operations & functions is available for sparse matrices:
fundamental arithmetic operations (such as addition and multiplication)
submatrix views: most contiguous forms and the non-contiguous form of X.cols(vector_of_column_indices)
diagonal views
saving and loading (using arma_binary, coord_ascii, and csv_ascii formats)
element-wise functions: abs(), ceil(), conj(), floor(), imag(), real(), round(), sign(), sqrt(), square(), trunc()
scalar functions of matrices: accu(), as_scalar(), dot(), norm(), trace()
vector valued functions of matrices: diagvec(), min(), max(), nonzeros(), sum(), mean(), var(), vectorise()
matrix valued functions of matrices: clamp(), diagmat(), flipud()/fliplr(), join_rows(), join_cols(), kron(), normalise(),
repelem(), repmat(), reshape(), resize(), reverse(), symmatu()/symmatl(), trimatu()/trimatl(), .t(), trans()
generated matrices: speye(), spones(), sprandu(), sprandn(), zeros()
arma.sourceforge.net/docs.html 16/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
eigen and svd decomposition: eigs_sym(), eigs_gen(), svds()
solution of sparse linear systems: spsolve()
miscellaneous: approx_equal(), element access, element iterators, .as_col() / .as_row(), .for_each(), .print(), .clean(),
.replace(), .transform(), .is_finite(), .is_symmetric(), .is_hermitian(), .is_trimatu(), .is_trimatl(), .is_diagmat()
Caveats:
the sparse matrix class is not intended for small matrices (eg. ≤ 100x100), due to the overhead of the compressed
storage format
for small matrices, use the dense matrix class, even if the vast majority of elements is zero
Examples:
sp_mat A = sprandu(1000, 2000, 0.01);
sp_mat B = sprandu(2000, 1000, 0.01);
sp_mat C = 2*B;
sp_mat D = A*C;
sp_mat E(1000,1000);
E(1,2) = 123;
umat locations = { { 1, 7, 9 },
{ 2, 8, 9 } };
See also:
element access
element iterators (sparse matrices)
printing matrices
Sparse Matrix in Wikipedia
Mat class (dense matrix)
arma.sourceforge.net/docs.html 17/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
operators: + − * % / == != <= >= < > && ||
Operations:
* matrix multiplication of two objects; not applicable to the Cube class unless multiplying by a scalar
>= element-wise "greater than or equal to" evaluation of two objects; generates a matrix/cube of type umat/ucube
<= element-wise "less than or equal to" evaluation of two objects; generates a matrix/cube of type umat/ucube
> element-wise "greater than" evaluation of two objects; generates a matrix/cube of type umat/ucube
< element-wise "less than" evaluation of two objects; generates a matrix/cube of type umat/ucube
&& element-wise logical AND evaluation of two objects; generates a matrix/cube of type umat/ucube
|| element-wise logical OR evaluation of two objects; generates a matrix/cube of type umat/ucube
For element-wise relational and logical operations (ie. ==, !=, >=, <=, >, <, &&, ||) each element in the generated object is
either 0 or 1, depending on the result of the operation
Caveat: operators involving equality comparison (ie. ==, !=, >=, <=) are not recommended for matrices of type mat or fmat,
due to the necessarily limited precision of the underlying element types; consider using approx_equal() instead
If the +, − and % operators are chained, Armadillo aims to avoid the generation of temporaries; no temporaries are generated if
all given objects are of the same type and size
If the * operator is chained, Armadillo aims to find an efficient ordering of the matrix multiplications
Examples:
mat A(5, 10, fill::randu);
mat B(5, 10, fill::randu);
mat C(10, 5, fill::randu);
mat P = A + B;
mat Q = A - B;
mat R = -B;
mat S = A / 123.0;
mat T = A % B;
mat U = A * C;
// compare elements
umat ZZ = (AA >= BB);
See also:
approx_equal()
powmat()
any()
all()
affmul()
accu()
as_scalar()
find()
.replace()
.transform()
.each_col() & .each_row() (vector operations repeated on each column or row)
miscellaneous element-wise functions (exp, log, pow, sqrt, square, round, ...)
floating point representation in Wikipedia
floating point representation in MathWorld
arma.sourceforge.net/docs.html 18/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
arma.sourceforge.net/docs.html 19/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
attributes
.n_rows number of rows; present in Mat, Col, Row, Cube, field and SpMat
.n_cols number of columns; present in Mat, Col, Row, Cube, field and SpMat
.n_elem total number of elements; present in Mat, Col, Row, Cube, field and SpMat
.n_slices number of slices; present in Cube and field
.n_nonzero number of non-zero elements; present in SpMat
The variables are read-only; to change the size, use .set_size(), .copy_size(), .zeros(), .ones(), or .reset()
For the Col and Row classes, n_elem also indicates vector length
Examples:
mat X(4,5);
cout << "X has " << X.n_cols << " columns" << endl;
See also:
.set_size()
.copy_size()
.zeros()
.ones()
.reset()
size()
arma.sourceforge.net/docs.html 20/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
element/object access via (), [] and .at()
Provide access to individual elements or objects stored in a container object (ie. Mat, Col, Row, Cube, field)
(n) For vec and rowvec, access the n-th element. For mat, cube and field, access the n-th element/object
under the assumption of a flat layout, with column-major ordering of data (ie. column by column). An
exception is thrown if the requested element is out of bounds. The bounds check can be optionally
disabled at compile-time to get more speed.
.at(n) or [n] As for (n), but without a bounds check. Not recommended for use unless your code has been thoroughly
debugged.
(i,j) For mat and 2D field classes, access the element/object stored at the i-th row and j-th column. An
exception is thrown if the requested element is out of bounds. The bounds check can be optionally
disabled at compile-time to get more speed.
.at(i,j) As for (i,j), but without a bounds check. Not recommended for use unless your code has been
thoroughly debugged.
(i,j,k) For cube and 3D field classes, access the element/object stored at the i-th row, j-th column and k-th
slice. An exception is thrown if the requested element is out of bounds. The bounds check can be
optionally disabled at compile-time to get more speed.
.at(i,j,k) As for (i,j,k), but without a bounds check. Not recommended for use unless your code has been
thoroughly debugged.
The bounds checks used by the (n), (i,j) and (i,j,k) element access forms can be disabled by defining the ARMA_NO_DEBUG
macro before including the armadillo header file (eg. #define ARMA_NO_DEBUG). Alternatively, the .at(n), .at(i,j) and .at(i,j,k)
element access forms can be used, which do not have bounds checks. Either way, disabling the bounds checks is not
recommended until your code has been thoroughly tested and debugged -- it is better to write correct code first, and then
maximise its speed.
Armadillo ≥ 10.3: the bounds checks throw std::out_of_range, derived from std::logic_error
Armadillo ≤ 10.2: the bounds checks throw std::logic_error
The indices of elements are specified via the uword type, which is a typedef for an unsigned integer type. When using loops to
access elements, it is best to use uword instead of int. For example: for(uword i=0; i<X.n_elem; ++i) { X(i) = ... }
Caveat: accessing elements via [i,j] and [i,j,k] does not work correctly in C++; instead use (i,j) and (i,j,k)
Examples:
mat A(10, 10, fill::randu);
A(9,9) = 123.0;
double x = A.at(9,9);
double y = A[99];
See also:
.in_range()
element initialisation
ind2sub()
sub2ind()
.index_min() / .index_max()
submatrix views
.memptr()
.transform()
.for_each()
iterators (dense matrices)
iterators (cubes)
iterators (sparse matrices)
config.hpp
arma.sourceforge.net/docs.html 21/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
element initialisation
Examples:
vec v = { 1, 2, 3 };
See also:
element access
.reshape()
.print()
saving & loading matrices
advanced constructors (matrices)
arma.sourceforge.net/docs.html 22/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.zeros() (member function of Mat, Col, Row, SpMat, Cube)
.zeros( n_elem ) (member function of Col and Row)
.zeros( n_rows, n_cols ) (member function of Mat and SpMat)
.zeros( n_rows, n_cols, n_slices ) (member function of Cube)
.zeros( size(X) ) (member function of Mat, Col, Row, Cube, SpMat)
Set the elements of an object to zero, optionally first changing the size to specified dimensions
Examples:
mat A;
A.zeros(5, 10); // or: mat A(5, 10, fill::zeros);
mat B;
B.zeros( size(A) );
See also:
zeros() (standalone function)
.ones()
.clean()
.is_zero()
.randu()
.fill()
.imbue()
.reset()
.set_size()
size()
arma.sourceforge.net/docs.html 23/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.ones() (member function of Mat, Col, Row, Cube)
.ones( n_elem ) (member function of Col and Row)
.ones( n_rows, n_cols ) (member function of Mat)
.ones( n_rows, n_cols, n_slices ) (member function of Cube)
.ones( size(X) ) (member function of Mat, Col, Row, Cube)
Set all the elements of an object to one, optionally first changing the size to specified dimensions
Examples:
mat A;
A.ones(5, 10); // or: mat A(5, 10, fill::ones);
mat B;
B.ones( size(A) );
See also:
ones() (standalone function)
.eye()
.zeros()
.fill()
.imbue()
.randu()
size()
arma.sourceforge.net/docs.html 24/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.eye()
.eye( n_rows, n_cols )
.eye( size(X) )
Set the elements along the main diagonal to one and off-diagonal elements to zero, optionally first changing the size to
specified dimensions
Examples:
mat A;
A.eye(5, 5); // or: mat A(5, 5, fill::eye);
mat B;
B.eye( size(A) );
See also:
.ones()
.diag()
diagmat()
diagvec()
eye() (standalone function)
size()
arma.sourceforge.net/docs.html 25/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.randu() (member function of Mat, Col, Row, Cube)
.randu( n_elem ) (member function of Col and Row)
.randu( n_rows, n_cols ) (member function of Mat)
.randu( n_rows, n_cols, n_slices ) (member function of Cube)
.randu( size(X) ) (member function of Mat, Col, Row, Cube)
Set all the elements to random values, optionally first changing the size to specified dimensions
.randn() uses a normal/Gaussian distribution with zero mean and unit variance
Examples:
mat A;
A.randu(5, 10); // or: mat A(5, 10, fill::randu);
mat B;
B.randu( size(A) );
See also:
randu() (standalone function with extended functionality)
randn() (standalone function with extended functionality)
.fill()
.imbue()
.ones()
.zeros()
size()
uniform distribution in Wikipedia
normal distribution in Wikipedia
arma.sourceforge.net/docs.html 26/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.fill( value )
The type of value must match the type of elements used by the container object (eg. for mat the type is double)
Examples:
mat A(5, 6);
A.fill(123.0);
Note: to explicitly set all elements to zero during object construction, use the following more compact form:
mat A(5, 6, fill::zeros);
See also:
.imbue()
.ones()
.zeros()
.randu() & .randn()
.replace()
constants (pi, nan, inf, ...)
arma.sourceforge.net/docs.html 27/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.imbue( functor )
.imbue( lambda_function )
For matrices, filling is done column-by-column (ie. column 0 is filled, then column 1, ...)
For cubes, filling is done slice-by-slice, with each slice treated as a matrix
Examples:
std::mt19937 engine; // Mersenne twister random number engine
See also:
.fill()
.transform()
element access
function object at Wikipedia
C++11 lambda functions at Wikipedia
lambda function at cprogramming.com
arma.sourceforge.net/docs.html 28/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.clean( threshold )
For objects with non-complex elements: each element with an absolute value ≤ threshold is replaced by zero
For objects with complex elements: for each element, each component (real and imaginary) with an absolute value ≤
threshold is replaced by zero
Can be used to sparsify a matrix, in the sense of zeroing values with small magnitudes
Caveat: to explicitly convert from dense storage to sparse storage, use the SpMat class
Examples:
sp_mat A;
A(12,34) = datum::eps;
A(56,78) = -datum::eps;
A.clean(datum::eps);
See also:
.replace()
.clamp()
.transform()
.is_zero()
.zeros()
nonzeros()
datum::eps
arma.sourceforge.net/docs.html 29/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.replace( old_value, new_value )
The type of old_value and new_value must match the type of elements used by the container object (eg. for mat the type is
double)
Caveats:
floating point numbers (float and double) are approximations due to their necessarily limited precision
for sparse matrices (SpMat), replacement is not done when old_value = 0
Examples:
mat A(5, 6, fill::randu);
A.diag().fill(datum::nan);
See also:
.transform()
.for_each()
.clean()
.clamp()
.fill()
.has_nan()
.has_inf()
find()
relational operators
constants (pi, nan, inf, ...)
arma.sourceforge.net/docs.html 30/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.clamp( min_value, max_value )
For complex elements, the real and imaginary components are clamped separately
Examples:
mat A(5, 6, fill::randu);
A.clamp(0.2, 0.8);
See also:
.replace()
.clean()
.transform()
.for_each()
clamp() (standalone function)
relational operators
arma.sourceforge.net/docs.html 31/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.transform( functor )
.transform( lambda_function )
For cubes, transformation is done slice-by-slice, with each slice treated as a matrix
Examples:
mat A(4, 5, fill::ones);
See also:
.for_each()
.replace()
.imbue()
.clean()
.clamp()
element access
overloaded operators
miscellaneous element-wise functions (exp, log, pow, sqrt, square, round, ...)
function object at Wikipedia
C++11 lambda functions at Wikipedia
lambda function at cprogramming.com
arma.sourceforge.net/docs.html 32/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.for_each( functor )
.for_each( lambda_function )
For dense matrices and fields, the processing is done column-by-column for all elements
For sparse matrices, the processing is done column-by-column for non-zero elements
For cubes, processing is done slice-by-slice, with each slice treated as a matrix
Examples:
// add 123 to each element in a dense matrix
field<mat> F(2,3);
See also:
.transform()
.replace()
.each_col() & .each_row()
.each_slice()
element access
miscellaneous element-wise functions (exp, log, pow, sqrt, square, round, ...)
function object at Wikipedia
C++11 lambda functions at Wikipedia
lambda function at cprogramming.com
arma.sourceforge.net/docs.html 33/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.set_size( n_elem ) (member function of Col, Row, field)
.set_size( n_rows, n_cols ) (member function of Mat, SpMat, field)
.set_size( n_rows, n_cols, n_slices ) (member function of Cube and field)
.set_size( size(X) ) (member function of Mat, Col, Row, Cube, SpMat, field)
Change the size of an object, without explicitly preserving data and without initialising the elements (ie. elements may
contain garbage values, including NaN)
To initialise the elements to zero while changing the size, use .zeros() instead
To explicitly preserve data while changing the size, use .reshape() or .resize() instead;
NOTE: .reshape() and .resize() are considerably slower than .set_size()
Examples:
mat A;
A.set_size(5, 10); // or: mat A(5, 10, fill::none);
mat B;
B.set_size( size(A) ); // or: mat B(size(A), fill::none);
vec v;
v.set_size(100); // or: vec v(100, fill::none);
See also:
.reset()
.copy_size()
.reshape()
.resize()
.zeros()
size()
arma.sourceforge.net/docs.html 34/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.reshape( n_rows, n_cols ) (member function of Mat and SpMat)
.reshape( n_rows, n_cols, n_slices ) (member function of Cube)
.reshape( size(X) ) (member function of Mat, Cube, SpMat)
Recreate the object according to given size specifications, with the elements taken from the previous version of the object in
a column-wise manner; the elements in the generated object are placed column-wise (ie. the first column is filled up before
filling the second column)
The layout of the elements in the recreated object will be different to the layout in the previous version of the object
If the total number of elements in the previous version of the object is less than the specified size, the extra elements in the
recreated object are set to zero
If the total number of elements in the previous version of the object is greater than the specified size, only a subset of the
elements is taken
Caveats:
do not use .reshape() to change the size without preserving data; use .set_size() instead, which is much faster
to grow/shrink the object while preserving the elements as well as the layout of the elements, use .resize() instead
to flatten a matrix into a vector, use vectorise() or .as_col() / .as_row() instead
Examples:
mat A(4, 5, fill::randu);
A.reshape(5,4);
See also:
.resize()
.set_size()
.copy_size()
.zeros()
.reset()
.as_col() / .as_row()
reshape() (standalone function)
vectorise()
size()
arma.sourceforge.net/docs.html 35/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.resize( n_elem ) (member function of Col, Row)
.resize( n_rows, n_cols ) (member function of Mat and SpMat)
.resize( n_rows, n_cols, n_slices ) (member function of Cube)
.resize( size(X) ) (member function of Mat, Col, Row, Cube, SpMat)
Recreate the object according to given size specifications, while preserving the elements as well as the layout of the elements
Can be used for growing or shrinking an object (ie. adding/removing rows, and/or columns, and/or slices)
Caveat: do not use .resize() to change the size without preserving data; use .set_size() instead, which is much faster
Examples:
mat A(4, 5, fill::randu);
A.resize(7,6);
See also:
.reshape()
.set_size()
.copy_size()
.zeros()
.reset()
.insert_rows/cols/slices
.shed_rows/cols/slices
resize() (standalone function)
vectorise()
size()
arma.sourceforge.net/docs.html 36/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.copy_size( A )
Object A must be of the same root type as the object being modified (eg. the size of a matrix can't be set by providing a cube)
Examples:
mat A(5, 6, fill::randu);
mat B;
B.copy_size(A);
See also:
.reset()
.set_size()
.reshape()
.resize()
.zeros()
size()
arma.sourceforge.net/docs.html 37/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.reset()
Examples:
mat A(5, 5, fill::randu);
A.reset();
See also:
.set_size()
.is_empty()
.zeros()
arma.sourceforge.net/docs.html 38/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
submatrix views
A collection of member functions of Mat, Col and Row classes that provide read/write access to submatrix views
X.head_cols( number_of_cols )
X.head_rows( number_of_rows )
X.tail_cols( number_of_cols )
X.tail_rows( number_of_rows )
V( span(first_index, last_index) )
V.subvec( first_index, last_index )
V.head( number_of_elements )
V.tail( number_of_elements )
For functions requiring one or more vector of indices, eg. X.submat(vector_of_row_indices, vector_of_column_indices), each
vector of indices must be of type uvec
In the function X.elem(vector_of_indices), elements specified in vector_of_indices are accessed. X is interpreted as one long
vector, with column-by-column ordering of the elements of X. The vector_of_indices must evaluate to a vector of type uvec
(eg. generated by the find() function). The aggregate set of the specified elements is treated as a column vector (ie. the
output of X.elem() is always a column vector).
The function .unsafe_col() is provided for speed reasons and should be used only if you know what you are doing. It creates a
seemingly independent Col vector object (eg. vec), but uses memory from the existing matrix object. As such, the created
vector is not alias safe, and does not take into account that the underlying matrix memory could be freed (eg. due to any
operation involving a size change of the matrix).
Examples:
mat A(5, 10, fill::zeros);
A.col(1) = randu<mat>(5,1);
A(span::all, 1) = randu<mat>(5,1);
X.elem(indices) = ones<vec>(4);
arma.sourceforge.net/docs.html 39/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
See also:
diagonal views
.each_col() & .each_row() (vector operations repeated on each column or row)
.colptr()
.in_range()
find()
join_rows/columns/slices
shed_rows/columns/slices
.insert_rows/cols/slices
size()
subcube views
arma.sourceforge.net/docs.html 40/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
subcube views and slices
A collection of member functions of the Cube class that provide subcube views
Q.head_slices( number_of_slices )
Q.tail_slices( number_of_slices )
An individual slice, accessed via .slice(), is an instance of the Mat class (a reference to a matrix is provided)
All .tube() forms are variants of .subcube(), using first_slice = 0 and last_slice = Q.n_slices-1
The .tube(row,col) form uses row = first_row = last_row, and col = first_col = last_col
In the function Q.elem(vector_of_indices), elements specified in vector_of_indices are accessed. Q is interpreted as one long
vector, with slice-by-slice and column-by-column ordering of the elements of Q. The vector_of_indices must evaluate to a
vector of type uvec (eg. generated by the find() function). The aggregate set of the specified elements is treated as a column
vector (ie. the output of Q.elem() is always a column vector).
Examples:
cube A(2, 3, 4, fill::randu);
A.slice(0) = randu<mat>(2,3);
A.slice(0)(1,2) = 99.0;
A.head_slices(2) += 123.0;
See also:
.in_range()
.each_slice()
join_slices()
shed_slices()
insert_slices()
size()
submatrix views
arma.sourceforge.net/docs.html 41/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
subfield views
A collection of member functions of the field class that provide subfield views
F.row( row_number )
F.col( col_number )
F.slice( slice_number )
See also:
.in_range()
size()
submatrix views
subcube views
arma.sourceforge.net/docs.html 42/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.diag()
.diag( k )
Examples:
mat X(5, 5, fill::randu);
vec a = X.diag();
vec b = X.diag(1);
vec c = X.diag(-2);
X.diag() = randu<vec>(5);
X.diag() += 6;
X.diag().ones();
sp_mat S = sprandu<sp_mat>(10,10,0.1);
See also:
.eye()
diagvec()
diagmat()
submatrix views
.each_col() & .each_row()
trace()
arma.sourceforge.net/docs.html 43/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.each_col()
.each_row()
.each_col( vector_of_indices )
.each_row( vector_of_indices )
.each_col( lambda_function )
.each_row( lambda_function )
The argument vector_of_indices is optional; by default all columns or rows are used
If the argument vector_of_indices is specified, it must evaluate to a vector of type uvec; the vector contains a list of indices
of the columns or rows to be used
If the lambda_function is specified, the function must accept a reference to a Col or Row object with the same element type
as the underlying matrix
Examples:
mat X(6, 5, fill::ones);
vec v = linspace<vec>(10,15,6);
uvec indices(2);
indices(0) = 2;
indices(1) = 4;
const mat& XX = X;
XX.each_col( [](const vec& b){ b.print(); } ); // lambda function with const vector
See also:
math & relational operators
submatrix views
diagonal views
repmat()
.for_each()
.each_slice()
arma.sourceforge.net/docs.html 44/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.each_slice() (form 1)
.each_slice( vector_of_indices ) (form 2)
.each_slice( lambda_function ) (form 3)
.each_slice( lambda_function, use_mp ) (form 4)
Apply a matrix operation to each slice of a cube, with each slice treated as a matrix
For form 2:
the argument vector_of_indices contains a list of indices of the slices to be used; it must evaluate to a vector of type
uvec
arithmetic operations as per form 1 are supported, except for * and *= (ie. matrix multiplication)
For form 3:
apply the given lambda_function to each slice; the function must accept a reference to a Mat object with the same
element type as the underlying cube
For form 4:
apply the given lambda_function to each slice, as per form 3
the argument use_mp is a bool which enables the use of OpenMP for multi-threaded execution of lambda_function on
multiple slices at the same time
the order of processing the slices is not deterministic (eg. slice 2 can be processed before slice 1)
lambda_function must be thread-safe, ie. it must not write to variables outside of its scope
Examples:
cube C(4, 5, 6, fill::randu);
uvec indices(2);
indices(0) = 2;
indices(1) = 4;
const cube& CC = C;
CC.each_slice( [](const mat& X){ X.print(); } ); // lambda function with const matrix
See also:
math & relational operators
subcube views
.for_each()
.each_col() & .each_row()
lambda function at cprogramming.com
arma.sourceforge.net/docs.html 45/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.set_imag( X )
.set_real( X )
Examples:
mat A(4, 5, fill::randu);
mat B(4, 5, fill::randu);
C.set_real(A);
C.set_imag(B);
Caveat: to directly construct a complex matrix out of two real matrices, the following code is faster:
mat A(4, 5, fill::randu);
mat B(4, 5, fill::randu);
cx_mat C = cx_mat(A,B);
See also:
matrix constructors
cube constructors
imag() / real()
arma.sourceforge.net/docs.html 46/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.insert_rows( row_number, X ) (member functions of Mat, Col and Cube)
.insert_rows( row_number, number_of_rows )
.insert_rows( row_number, number_of_rows, set_to_zero )
Examples:
mat A(5, 10, fill::randu);
mat B(5, 2, fill::ones );
See also:
shed_rows/columns/slices
join_rows/columns/slices
.resize()
submatrix views
subcube views
arma.sourceforge.net/docs.html 47/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.shed_row( row_number ) (member function of Mat, Col, SpMat, Cube)
.shed_rows( first_row, last_row ) (member function of Mat, Col, SpMat, Cube)
.shed_rows( vector_of_indices ) (member function of Mat, Col)
Functions with two scalar arguments: remove the specified range of rows/columns/slices
The vector_of_indices must evaluate to a vector of type uvec; it contains the indices of rows/columns/slices to remove
Examples:
mat A(5, 10, fill::randu);
mat B(5, 10, fill::randu);
A.shed_row(2);
A.shed_cols(2,4);
See also:
insert_rows/columns/slices
join_rows/columns/slices
.resize()
submatrix views
subcube views
shed in thesaurus.com
arma.sourceforge.net/docs.html 48/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.swap_rows( row1, row2 )
.swap_cols( col1, col2 )
Examples:
mat X(5, 5, fill::randu);
X.swap_rows(0,4);
See also:
reverse()
fliplr() & flipud()
.swap()
arma.sourceforge.net/docs.html 49/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.swap( X )
Examples:
mat A(4, 5, fill::zeros);
mat B(6, 7, fill::ones );
A.swap(B);
See also:
.swap_rows() & .swap_cols()
arma.sourceforge.net/docs.html 50/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.memptr()
The function can be used for interfacing with libraries such as FFTW
Caveat: the pointer becomes invalid after any operation involving a size change or aliasing
Caveat: this function is not recommended for use unless you know what you are doing!
Examples:
mat A(5, 5, fill::randu);
const mat B(5, 5, fill::randu);
See also:
.colptr()
element access
iterators (dense matrices)
iterators (cubes)
advanced constructors (matrices)
advanced constructors (cubes)
arma.sourceforge.net/docs.html 51/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.colptr( col_number )
Caveat: the pointer becomes invalid after any operation involving a size change or aliasing
Caveat: this function is not recommended for use unless you know what you are doing -- it is safer to use submatrix views
instead
Examples:
mat A(5, 5, fill::randu);
See also:
.memptr()
submatrix views
element access
iterators (dense matrices)
advanced constructors (matrices)
arma.sourceforge.net/docs.html 52/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
iterators (dense matrices & vectors)
Iterators for dense matrices and vectors traverse over all elements within the specified range
Member functions:
.begin_col( col_number ) iterator referring to the first element of the specified column
.end_col( col_number ) iterator referring to the past-the-end element of the specified column
.begin_row( row_number ) iterator referring to the first element of the specified row
.end_row( row_number ) iterator referring to the past-the-end element of the specified row
Iterator types:
mat::iterator random access iterators, for read/write access to elements (which are stored column by
vec::iterator column)
rowvec::iterator
mat::const_iterator random access iterators, for read-only access to elements (which are stored column by
vec::const_iterator column)
rowvec::const_iterator
mat::col_iterator random access iterators, for read/write access to the elements of specified columns
vec::col_iterator
rowvec::col_iterator
mat::const_col_iterator random access iterators, for read-only access to the elements of specified columns
vec::const_col_iterator
rowvec::const_col_iterator
mat::row_iterator bidirectional iterator, for read/write access to the elements of specified rows
mat::const_row_iterator bidirectional iterator, for read-only access to the elements of specified rows
vec::row_iterator random access iterators, for read/write access to the elements of specified rows
rowvec::row_iterator
vec::const_row_iterator random access iterators, for read-only access to the elements of specified rows
rowvec::const_row_iterator
Examples:
mat X(5, 6, fill::randu);
mat::iterator it = X.begin();
mat::iterator it_end = X.end();
See also:
Mat class
element access
.for_each()
.memptr()
.colptr()
submatrix views
iterators (submatrices)
iterators (cubes)
iterators (sparse matrices)
iterator at cplusplus.com
arma.sourceforge.net/docs.html 53/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
iterators (cubes)
Iterators for cubes traverse over all elements within the specified range
Member functions:
.begin_slice( slice_number ) iterator referring to the first element of the specified slice
.end_slice( slice_number ) iterator referring to the past-the-end element of the specified slice
Iterator types:
cube::iterator random access iterator, for read/write access to elements; the elements are ordered slice
by slice; the elements within each slice are ordered column by column
cube::slice_iterator random access iterator, for read/write access to the elements of a particular slice; the
elements are ordered column by column
cube::const_slice_iterator random access iterator, for read-only access to the elements of a particular slice
Examples:
cube X(2, 3, 4, fill::randu);
cube::iterator it = X.begin();
cube::iterator it_end = X.end();
See also:
Cube class
element access
.for_each()
.memptr()
subcube views
iterators (subcubes)
iterators (dense matrices)
iterator at cplusplus.com
arma.sourceforge.net/docs.html 54/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
iterators (sparse matrices)
Iterators for sparse matrices traverse over non-zero elements within the specified range
Caveats:
to modify the non-zero elements in a safer manner, use .transform() or .for_each() instead of iterators;
writing a zero value into a sparse matrix through an iterator will invalidate all current iterators associated with the
sparse matrix
Member functions:
.begin_col( col_number ) iterator referring to the first element of the specified column
.end_col( col_number ) iterator referring to the past-the-end element of the specified column
.begin_row( row_number ) iterator referring to the first element of the specified row
.end_row( row_number ) iterator referring to the past-the-end element of the specified row
Iterator types:
sp_mat::iterator bidirectional iterator, for read/write access to elements (which are stored column by
column)
sp_mat::const_iterator bidirectional iterator, for read-only access to elements (which are stored column by
column)
sp_mat::col_iterator bidirectional iterator, for read/write access to the elements of a specific column
sp_mat::const_col_iterator bidirectional iterator, for read-only access to the elements of a specific column
sp_mat::row_iterator bidirectional iterator, for read/write access to the elements of a specific row
sp_mat::const_row_iterator bidirectional iterator, for read-only access to the elements of a specific row
The iterators have .row() and .col() functions which return the row and column of the current element; the returned values
are of type uword
Examples:
sp_mat X = sprandu<sp_mat>(1000, 2000, 0.1);
sp_mat::const_iterator it = X.begin();
sp_mat::const_iterator it_end = X.end();
See also:
SpMat class
element access
.transform()
.for_each()
.replace()
submatrix views
iterators (dense matrices)
iterator at cplusplus.com
arma.sourceforge.net/docs.html 55/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
iterators (dense submatrices & subcubes)
iterators for dense submatrix and subcube views, allowing range-based for loops
Caveat: These iterators are intended only to be used with range-based for loops. Any other use is not supported. For example,
the direct use of the begin() and end() functions, as well as the underlying iterators types is not supported. The
implementation of submatrices and subcubes uses short-lived temporary objects that are subject to automatic deletion, and
as such are error-prone to handle manually.
Examples:
mat X(100, 200, fill::randu);
See also:
submatrix views
.for_each()
iterators (dense matrices)
iterators (cubes)
range-based for (cppreference.com)
arma.sourceforge.net/docs.html 56/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
compatibility container functions
Member functions to mimic the functionality of containers in the C++ standard library:
Examples:
mat A(5, 5, fill::randu);
cout << A.size() << endl;
A.clear();
cout << A.empty() << endl;
See also:
iterators (dense matrices)
iterators (cubes)
iterators (sparse matrices)
matrix and vector attributes
.is_empty()
.reset()
arma.sourceforge.net/docs.html 57/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.as_col()
.as_row()
.as_col(): return a flattened version of the matrix as a column vector; flattening is done by concatenating all columns
.as_row(): return a flattened version of the matrix as a row vector; flattening is done by concatenating all rows
Examples:
mat X(4, 5, fill::randu);
vec v = X.as_col();
See also:
.reshape()
.t() / .st()
as_scalar()
vectorise()
arma.sourceforge.net/docs.html 58/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.t()
.st()
Examples:
mat A(4, 5, fill::randu);
mat B = A.t();
See also:
trans()
reverse()
.as_col() / .as_row()
transpose in Wikipedia
transpose in MathWorld
conjugate transpose in Wikipedia
conjugate transpose in MathWorld
arma.sourceforge.net/docs.html 59/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.i()
If the matrix expression appears to be singular, the output matrix is reset and a std::runtime_error exception is thrown
Caveats:
if matrix A is know to be symmetric positive definite, it is faster to use inv_sympd() instead
to solve a system of linear equations, such as Z = inv(X)*Y, using solve() can be faster and/or more accurate
Examples:
mat A(4, 4, fill::randu);
mat X = A.i();
mat Y = (A+A).i();
See also:
inv()
rcond()
pinv()
solve()
spsolve()
arma.sourceforge.net/docs.html 60/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.min()
.max()
For objects with complex numbers, absolute values are used for comparison
Examples:
mat A(5, 5, fill::randu);
See also:
.index_min() & .index_max()
min() & max() (standalone functions with extended functionality)
clamp()
running_stat
running_stat_vec
arma.sourceforge.net/docs.html 61/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.index_min()
.index_max()
Return the linear index of the extremum value of any matrix or cube expression
For objects with complex numbers, absolute values are used for comparison
Examples:
mat A(5, 5, fill::randu);
uword i = A.index_max();
See also:
.min() & .max()
index_min() & index_max() (standalone functions with extended functionality)
ind2sub()
sort_index()
find()
element access
arma.sourceforge.net/docs.html 62/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.eval()
This function should be used sparingly and only in cases where it is absolutely necessary; indiscriminate use can degrade
performance
Examples:
cx_mat A( randu<mat>(4,4), randu<mat>(4,4) );
real(A).eval().save("A_real.dat", raw_ascii);
imag(A).eval().save("A_imag.dat", raw_ascii);
See also:
as_scalar()
Mat class
arma.sourceforge.net/docs.html 63/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.in_range( i ) (member of Mat, Col, Row, Cube, SpMat, field)
.in_range( span(start, end) ) (member of Mat, Col, Row, Cube, SpMat, field)
.in_range( first_row, first_col, size(X) ) (X is a matrix or field) (member of Mat, Col, Row, SpMat, field)
.in_range( first_row, first_col, size(n_rows, n_cols) ) (member of Mat, Col, Row, SpMat, field)
.in_range( first_row, first_col, first_slice, size(Q) ) (Q is a cube or field) (member of Cube and field)
.in_range( first_row, first_col, first_slice, size(n_rows, n_cols n_slices) ) (member of Cube and field)
Returns false if the object is empty, the location is out of bounds, or the span is out of bounds
Examples:
mat A(4, 5, fill::randu);
See also:
element access
submatrix views
subcube views
subfield views
.set_size()
arma.sourceforge.net/docs.html 64/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.is_empty()
Examples:
mat A(5, 5, fill::randu);
cout << A.is_empty() << endl;
A.reset();
cout << A.is_empty() << endl;
See also:
.is_square()
.is_vec()
.is_finite()
.reset()
arma.sourceforge.net/docs.html 65/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.is_vec()
.is_colvec()
.is_rowvec()
.is_vec():
returns true if the matrix can be interpreted as a vector (either column or row vector)
returns false if the matrix does not have exactly one column or one row
.is_colvec():
returns true if the matrix can be interpreted as a column vector
returns false if the matrix does not have exactly one column
.is_rowvec():
returns true if the matrix can be interpreted as a row vector
returns false if the matrix does not have exactly one row
Caveat: do not assume that the vector has elements if these functions return true; it is possible to have an empty vector (eg.
0x1)
Examples:
mat A(1, 5, fill::randu);
mat B(5, 1, fill::randu);
mat C(5, 5, fill::randu);
See also:
.is_empty()
.is_square()
.is_finite()
arma.sourceforge.net/docs.html 66/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.is_sorted()
.is_sorted( sort_direction )
.is_sorted( sort_direction, dim )
If the object is a vector, return a bool indicating whether the elements are sorted
If the object is a matrix, return a bool indicating whether the elements are sorted in each column (dim = 0), or each row (dim
= 1)
For matrices and vectors with complex numbers, order is checked via absolute values
Examples:
vec a(10, fill::randu);
vec b = sort(a);
See also:
sort()
sort_index()
arma.sourceforge.net/docs.html 67/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.is_trimatu()
.is_trimatl()
.is_trimatu():
return true if the matrix is upper triangular, ie. the matrix is square sized and all elements below the main diagonal are
zero; return false otherwise
caveat: if this function returns true, do not assume that the matrix contains non-zero elements on or above the main
diagonal
.is_trimatl():
return true if the matrix is lower triangular, ie. the matrix is square sized and all elements above the main diagonal are
zero; return false otherwise
caveat: if this function returns true, do not assume that the matrix contains non-zero elements on or below the main
diagonal
Examples:
mat A(5, 5, fill::randu);
mat B = trimatl(A);
See also:
trimatu() / trimatl()
.is_symmetric()
.is_diagmat()
Triangular matrix in MathWorld
Triangular matrix in Wikipedia
arma.sourceforge.net/docs.html 68/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.is_diagmat()
Return true if the matrix is diagonal, ie. all elements outside of the main diagonal are zero
Caveat: if this function returns true, do not assume that the matrix contains non-zero elements on the main diagonal
Examples:
mat A(5, 5, fill::randu);
mat B = diagmat(A);
See also:
diagmat()
.is_trimatu() / .is_trimatl()
.is_symmetric()
Diagonal matrix in MathWorld
Diagonal matrix in Wikipedia
arma.sourceforge.net/docs.html 69/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.is_square()
Returns true if the matrix is square, ie. number of rows is equal to the number of columns
Examples:
mat A(5, 5, fill::randu);
mat B(6, 7, fill::randu);
See also:
.is_symmetric()
.is_hermitian()
.is_empty()
.is_vec()
.is_finite()
arma.sourceforge.net/docs.html 70/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.is_symmetric()
.is_symmetric( tol )
The tol argument is optional; if tol is specified, the given matrix X is considered symmetric if norm(X - X.st(), "inf") / norm (X,
"inf") ≤ tol
Examples:
mat A(5, 5, fill::randu);
mat B = A.t() * A;
See also:
.is_hermitian()
.is_sympd()
.is_square()
.is_trimatu() / .is_trimatl()
Symmetric matrix in Wikipedia
Symmetric matrix in MathWorld
arma.sourceforge.net/docs.html 71/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.is_hermitian()
.is_hermitian( tol )
The tol argument is optional; if tol is specified, the given matrix X is considered hermitian if norm(X - X.t(), "inf") / norm (X,
"inf") ≤ tol
Examples:
cx_mat A(5, 5, fill::randu);
cx_mat B = A.t() * A;
See also:
.is_symmetric()
.is_sympd()
.is_square()
Hermitian matrix in Wikipedia
Hermitian matrix in MathWorld
arma.sourceforge.net/docs.html 72/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.is_sympd()
.is_sympd( tol )
Returns true if the matrix is symmetric/hermitian positive definite within the tolerance given by tol
The tol argument is optional; if tol is not specified, by default tol = 100 * datum::eps * norm(X, "fro")
Examples:
mat A(5, 5, fill::randu);
mat B = A.t() * A;
See also:
.is_symmetric()
.is_hermitian()
datum::eps
arma.sourceforge.net/docs.html 73/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.is_zero()
.is_zero( tolerance )
For objects with non-complex elements: return true if each element has an absolute value ≤ tolerance; return false otherwise
For objects with complex elements: return true if for each element, each component (real and imaginary) has an absolute
value ≤ tolerance; return false otherwise
Examples:
mat A(5, 5, fill::zeros);
A(0,0) = datum::eps;
See also:
.clean()
all()
datum::eps
approx_equal()
arma.sourceforge.net/docs.html 74/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.is_finite()
Returns false if at least one of the elements of the object is non-finite (±infinity or NaN)
Examples:
mat A(5, 5, fill::randu);
mat B(5, 5, fill::randu);
B(1,1) = datum::inf;
See also:
.has_inf()
.has_nan()
find_finite()
find_nonfinite()
constants (pi, nan, inf, ...)
arma.sourceforge.net/docs.html 75/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.has_inf()
Examples:
mat A(5, 5, fill::randu);
mat B(5, 5, fill::randu);
B(1,1) = datum::inf;
See also:
.has_nan()
.replace()
.is_finite()
find_nonfinite()
constants (pi, nan, inf, ...)
arma.sourceforge.net/docs.html 76/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.has_nan()
Returns true if at least one of the elements of the object is NaN (not-a-number)
Examples:
mat A(5, 5, fill::randu);
mat B(5, 5, fill::randu);
B(1,1) = datum::nan;
See also:
.has_inf()
.replace()
.is_finite()
find_nonfinite()
constants (pi, nan, inf, ...)
arma.sourceforge.net/docs.html 77/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.print()
.print( header )
.print( stream )
.print( stream, header )
Print the contents of an object to the std::cout stream (default), or a user specified stream, with an optional header string
Elements of a field can only be printed if there is an associated operator<< function defined
Examples:
mat A(5, 5, fill::randu);
mat B(6, 6, fill::randu);
A.print();
See also:
.raw_print()
.brief_print()
saving & loading matrices
initialising elements
output streams
arma.sourceforge.net/docs.html 78/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.raw_print()
.raw_print( header )
.raw_print( stream )
.raw_print( stream, header )
Similar to the .print() member function, with the difference that no formatting of the output is done; the stream's parameters
such as precision, cell width, etc. can be set manually
If the cell width is set to zero, a space is printed between the elements
Examples:
mat A(5, 5, fill::randu);
cout.precision(11);
cout.setf(ios::fixed);
A.raw_print(cout, "A:");
See also:
.print()
.brief_print()
std::ios_base::fmtflags (cppreference.com)
std::ios_base::fmtflags (cplusplus.com)
arma.sourceforge.net/docs.html 79/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.brief_print()
.brief_print( header )
.brief_print( stream )
.brief_print( stream, header )
Similar to the .print() member function, with the difference that an abridged version of the object is printed
Examples:
mat A(123, 456, fill::randu);
A.brief_print("A:");
// possible output:
//
// A:
// [matrix size: 123x456]
// 0.8402 0.7605 0.6218 ... 0.9744
// 0.3944 0.9848 0.0409 ... 0.7799
// 0.7831 0.9350 0.4140 ... 0.8835
// : : : : :
// 0.4954 0.1826 0.9848 ... 0.1918
See also:
.print()
.raw_print()
arma.sourceforge.net/docs.html 80/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
saving/loading matrices & cubes
Store/retrieve data in a file or stream (caveat: the stream must be opened in binary mode)
On failure, .save() and .load() return a bool set to false; additionally, .load() resets the object so that it has no elements
auto_detect Used only by .load() only: attempt to automatically detect the file type as one of the formats described
below;
[ default operation for .load() ]
arma_binary Numerical data stored in machine dependent binary format, with a simple header to speed up loading.
The header indicates the type and size of matrix/cube.
[ default operation for .save() ]
arma_ascii Numerical data stored in human readable text format, with a simple header to speed up loading. The
header indicates the type and size of matrix/cube.
raw_binary Numerical data stored in machine dependent raw binary format, without a header. Matrices are loaded to
have one column, while cubes are loaded to have one slice with one column. The .reshape() function can
be used to alter the size of the loaded matrix/cube without losing data.
raw_ascii Numerical data stored in raw ASCII format, without a header. The numbers are separated by whitespace.
The number of columns must be the same in each row. Cubes are loaded as one slice. Data which was
saved in Matlab/Octave using the -ascii option can be read in Armadillo, except for complex numbers.
Complex numbers are stored in standard C++ notation, which is a tuple surrounded by brackets: eg.
(1.23,4.56) indicates 1.24 + 4.56i.
csv_ascii Numerical data stored in comma separated value (CSV) text format, without a header. To save/load with
a header, use the csv_name(filename,header) specification instead (more details below). Handles
complex numbers stored in the compound form of 1.24+4.56i. Applicable to Mat and SpMat.
coord_ascii Numerical data stored as a text file in coordinate list format, without a header. Only non-zero values are
stored.
For real matrices, each line contains information in the following format: row column value
For complex matrices, each line contains information in the following format: row column real_value
imag_value
The rows and columns start at zero.
Armadillo ≥ 10.3: applicable to Mat and SpMat; Armadillo ≤ 10.2: applicable to SpMat only.
Caveat: not supported by auto_detect.
pgm_binary Image data stored in Portable Gray Map (PGM) format. Applicable to Mat only. Saving int, float or double
matrices is a lossy operation, as each element is copied and converted to an 8 bit representation. As such
the matrix should have values in the [0,255] interval, otherwise the resulting image may not display
correctly.
ppm_binary Image data stored in Portable Pixel Map (PPM) format. Applicable to Cube only. Saving int, float or double
matrices is a lossy operation, as each element is copied and converted to an 8 bit representation. As such
the cube/field should have values in the [0,255] interval, otherwise the resulting image may not display
correctly.
By providing either hdf5_name(filename, dataset) or hdf5_name(filename, dataset, settings), the file_type type is assumed
to be hdf5_binary
arma.sourceforge.net/docs.html 81/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
the dataset argument specifies an HDF5 dataset name (eg. "my_dataset") that can include a full path (eg.
"/group_name/my_dataset"); if a blank dataset name is specified (ie. ""), it is assumed to be "dataset"
hdf5_opts::trans save/load the data with columns transposed to rows (and vice versa)
hdf5_opts::append instead of overwriting the file, append the specified dataset to the file;
the specified dataset must not already exist in the file
hdf5_opts::replace instead of overwriting the file, replace the specified dataset in the file
caveat: HDF5 v1.8 may not automatically reclaim deleted space; use h5repack to clean HDF5 files
the above settings can be combined using the + operator; for example: hdf5_opts::trans + hdf5_opts::append
Caveat: for saving/loading HDF5 files, support for HDF5 must be enabled within Armadillo's configuration; the hdf5.h header
file must be available on your system and you will need to link with the HDF5 library (eg. -lhdf5)
By providing either csv_name(filename, header) or csv_name(filename, header, settings), the file is assumed to have data in
comma separated value (CSV) text format
the header argument specifies the object which stores the separate elements of the header line; it must have the type
field<std::string>
csv_opts::trans save/load the data with columns transposed to rows (and vice versa)
csv_opts::no_header assume there is no header line; the header argument is not referenced
csv_opts::semicolon use semicolon (;) instead of comma (,) as the separator character (Armadillo 10.6 and later)
the above settings can be combined using the + operator; for example: csv_opts::trans + csv_opts::no_header
Examples:
mat A(5, 6, fill::randu);
if(ok == false)
{
cout << "problem with loading" << endl;
}
See also:
HDF in Wikipedia
CSV in Wikipedia
saving/loading fields
arma.sourceforge.net/docs.html 82/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
saving/loading fields
Store/retrieve data in a file or stream (caveat: the stream must be opened in binary mode)
On failure, .save() and .load() return a bool set to false; additionally, .load() resets the object so that it has no elements
Fields with objects of type std::string are saved and loaded as raw text files. The text files do not have a header. Each string
is separated by a whitespace. load() will only accept text files that have the same number of strings on each line. The strings
can have variable lengths.
Other than storing string fields as text files, the following file formats are supported:
auto_detect
.load(): attempt to automatically detect the field format type as one of the formats described below; this
is the default operation
arma_binary
objects are stored in machine dependent binary format
default type for fields of type Mat, Col, Row or Cube
only applicable to fields of type Mat, Col, Row or Cube
ppm_binary
image data stored in Portable Pixmap Map (PPM) format
only applicable to fields of type Mat, Col or Row
.load(): loads the specified image and stores the red, green and blue components as three separate
matrices; the resulting field is comprised of the three matrices, with the red, green and blue components
in the first, second and third matrix, respectively
.save(): saves a field with exactly three matrices of equal size as an image; it is assumed that the red,
green and blue components are stored in the first, second and third matrix, respectively; saving int, float
or double matrices is a lossy operation, as each matrix element is copied and converted to an 8 bit
representation
See also:
saving/loading matrices and cubes
arma.sourceforge.net/docs.html 83/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Generated Vectors/Matrices/Cubes
arma.sourceforge.net/docs.html 84/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
linspace( start, end )
linspace( start, end, N )
Generate a vector with N elements; the values of the elements are linearly spaced from start to (and including) end
Usage:
vec v = linspace(start, end, N)
vector_type v = linspace<vector_type>(start, end, N)
Caveat: for N = 1, the generated vector will have a single element equal to end
Examples:
vec a = linspace(0, 5, 6);
See also:
regspace()
logspace()
randperm()
ones()
interp1()
arma.sourceforge.net/docs.html 85/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
logspace( A, B )
logspace( A, B, N )
Generate a vector with N elements; the values of the elements are logarithmically spaced from 10A to (and including) 10B
Usage:
vec v = logspace(A, B, N)
vector_type v = logspace<vector_type>(A, B, N)
Examples:
vec a = logspace(0, 5, 6);
See also:
linspace()
regspace()
arma.sourceforge.net/docs.html 86/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
regspace( start, end )
regspace( start, delta, end )
Similar in operation to the Matlab/Octave colon operator, ie. start:end and start:delta:end
Usage:
vec v = regspace(start, end)
vec v = regspace(start, delta, end)
vector_type v = regspace<vector_type>(start, end)
vector_type v = regspace<vector_type>(start, delta, end)
Examples:
vec a = regspace(0, 9); // 0, 1, ..., 9
Caveat: do not use regspace() to specify ranges for contiguous submatrix views; use span() instead
See also:
linspace()
logspace()
arma.sourceforge.net/docs.html 87/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
randperm( N )
randperm( N, M )
The optional argument M indicates the number of elements to return, sampled without replacement from 0 to N-1
Examples:
uvec X = randperm(10);
uvec Y = randperm(10,2);
See also:
randi()
linspace()
regspace()
arma.sourceforge.net/docs.html 88/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
eye( n_rows, n_cols )
eye( size(X) )
Generate a matrix with the elements along the main diagonal set to one and off-diagonal elements set to zero
Usage:
mat X = eye( n_rows, n_cols )
matrix_type X = eye<matrix_type>( n_rows, n_cols )
matrix_type Y = eye<matrix_type>( size(X) )
Examples:
mat A = eye(5,5); // or: mat A(5,5,fill::eye);
See also:
.eye() (member function of Mat)
.diag()
ones()
diagmat()
diagvec()
speye()
size()
arma.sourceforge.net/docs.html 89/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
ones( n_elem )
ones( n_rows, n_cols )
ones( n_rows, n_cols, n_slices )
ones( size(X) )
Usage:
vector_type v = ones<vector_type>( n_elem )
matrix_type X = ones<matrix_type>( n_rows, n_cols )
matrix_type Y = ones<matrix_type>( size(X) )
cube_type Q = ones<cube_type>( n_rows, n_cols, n_slices )
cube_type R = ones<cube_type>( size(Q) )
Examples:
vec v = ones(10); // or: vec v(10, fill::ones);
uvec u = ones<uvec>(10);
rowvec r = ones<rowvec>(10);
See also:
.ones() (member function of Mat, Col, Row and Cube)
eye()
linspace()
regspace()
randperm()
zeros()
randu()
spones()
size()
arma.sourceforge.net/docs.html 90/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
zeros( n_elem )
zeros( n_rows, n_cols )
zeros( n_rows, n_cols, n_slices )
zeros( size(X) )
Usage:
vector_type v = zeros<vector_type>( n_elem )
matrix_type X = zeros<matrix_type>( n_rows, n_cols )
matrix_type Y = zeros<matrix_type>( size(X) )
cube_type Q = zeros<cube_type>( n_rows, n_cols, n_slices )
cube_type R = zeros<cube_type>( size(Q) )
Examples:
vec v = zeros(10); // or: vec v(10, fill::zeros);
uvec u = zeros<uvec>(10);
rowvec r = zeros<rowvec>(10);
See also:
.zeros() (member function of Mat, Col, Row, SpMat and Cube)
.ones() (member function of Mat, Col, Row and Cube)
ones()
randu()
size()
arma.sourceforge.net/docs.html 91/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
randu( )
randu( distr_param(a,b) )
randu( n_elem )
randu( n_elem, distr_param(a,b) )
randu( size(X) )
randu( size(X), distr_param(a,b) )
Generate a scalar, vector, matrix or cube with the elements set to random floating point values uniformly distributed in the
[a,b] interval
Usage:
scalar_type s = randu<scalar_type>( ), where scalar_type ∈ { float, double, cx_float, cx_double }
scalar_type s = randu<scalar_type>( distr_param(a,b) ), where scalar_type ∈ { float, double, cx_float, cx_double }
Caveat: to generate a matrix with random integer values instead of floating point values, use randi() instead
Examples:
double a = randu();
double b = randu(distr_param(10,20));
rowvec r1 = randu<rowvec>(5);
rowvec r2 = randu<rowvec>(5, distr_param(10,20));
See also:
.randu() (member function)
randn()
randg()
randi()
.imbue()
ones()
zeros()
shuffle()
sprandu()
size()
uniform distribution in Wikipedia
arma.sourceforge.net/docs.html 92/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
randn( )
randn( distr_param(mu,sd) )
randn( n_elem )
randn( n_elem, distr_param(mu,sd) )
randn( size(X) )
randn( size(X), distr_param(mu,sd) )
Generate a scalar, vector, matrix or cube with the elements set to random values with normal / Gaussian distribution,
parameterised by mean mu and standard deviation sd
Usage:
scalar_type s = randn<scalar_type>( ), where scalar_type ∈ { float, double, cx_float, cx_double }
scalar_type s = randn<scalar_type>( distr_param(mu,sd) ), where scalar_type ∈ { float, double, cx_float, cx_double }
Examples:
double a = randn();
double b = randn(distr_param(10,5));
rowvec r1 = randn<rowvec>(5);
rowvec r2 = randn<rowvec>(5, distr_param(10,5));
See also:
.randn() (member function)
randu()
randg()
randi()
mvnrnd()
normpdf()
.imbue()
sprandn()
size()
normal distribution in Wikipedia
arma.sourceforge.net/docs.html 93/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
randg( )
randg( distr_param(a,b) )
randg( n_elem )
randg( n_elem, distr_param(a,b) )
randg( size(X) )
randg( size(X), distr_param(a,b) )
Generate a scalar, vector, matrix or cube with the elements set to random values from a gamma distribution:
x a-1 exp( -x / b )
p(x | a,b) =
b a Γ(a)
where a is the shape parameter and b is the scale parameter, with constraints a > 0 and b > 0
Usage:
scalar_type s = randg<scalar_type>( ), where scalar_type is either float or double
scalar_type s = randg<scalar_type>( distr_param(a,b) ), where scalar_type is either float or double
Examples:
vec v1 = randg(100);
vec v2 = randg(100, distr_param(2,1));
rowvec r1 = randg<rowvec>(100);
rowvec r2 = randg<rowvec>(100, distr_param(2,1));
See also:
randu()
randn()
randi()
chi2rnd()
.imbue()
size()
gamma distribution in Wikipedia
arma.sourceforge.net/docs.html 94/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
randi( )
randi( distr_param(a,b) )
randi( n_elem )
randi( n_elem, distr_param(a,b) )
randi( size(X) )
randi( size(X), distr_param(a,b) )
Generate a scalar, vector, matrix or cube with the elements set to random integer values uniformly distributed in the [a,b]
interval
Usage:
scalar_type v = randi<scalar_type>( )
scalar_type v = randi<scalar_type>( distr_param(a,b) )
Caveat: to generate a matrix with random floating point values (ie. float or double) instead of integers, use randu() instead
Examples:
int a = randi();
int b = randi(distr_param(-10, +20));
See also:
randu()
randperm()
.imbue()
ones()
zeros()
shuffle()
size()
arma.sourceforge.net/docs.html 95/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
speye( n_rows, n_cols )
speye( size(X) )
Generate a sparse matrix with the elements along the main diagonal set to one and off-diagonal elements set to zero
Usage:
sparse_matrix_type X = speye<sparse_matrix_type>( n_rows, n_cols )
sparse_matrix_type Y = speye<sparse_matrix_type>( size(X) )
Examples:
sp_mat A = speye<sp_mat>(5,5);
See also:
spones()
sprandu() & sprandn()
eye()
size()
arma.sourceforge.net/docs.html 96/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
spones( A )
Generate a sparse matrix with the same structure as sparse matrix A, but with the non-zero elements set to one
Examples:
sp_mat A = sprandu<sp_mat>(100, 200, 0.1);
sp_mat B = spones(A);
See also:
speye()
sprandu() & sprandn()
ones()
arma.sourceforge.net/docs.html 97/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
sprandu( n_rows, n_cols, density )
sprandn( n_rows, n_cols, density )
Generate a sparse matrix with the non-zero elements set to random values
The density argument specifies the percentage of non-zero elements; it must be in the [0,1] interval
sprandn() uses a normal/Gaussian distribution with zero mean and unit variance
Usage:
sparse_matrix_type X = sprandu<sparse_matrix_type>( n_rows, n_cols, density )
sparse_matrix_type Y = sprandu<sparse_matrix_type>( size(X), density )
Examples:
sp_mat A = sprandu<sp_mat>(100, 200, 0.1);
See also:
speye()
spones()
randu()
randn()
size()
uniform distribution in Wikipedia
normal distribution in Wikipedia
arma.sourceforge.net/docs.html 98/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
toeplitz( A )
toeplitz( A, B )
circ_toeplitz( A )
toeplitz(): generate a Toeplitz matrix, with the first column specified by A, and (optionally) the first row specified by B
Examples:
vec A(5, fill::randu);
mat X = toeplitz(A);
mat Y = circ_toeplitz(A);
See also:
Toeplitz matrix in MathWorld
Toeplitz matrix in Wikipedia
Circulant matrix in Wikipedia
arma.sourceforge.net/docs.html 99/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Functions of Vectors/Matrices/Cubes
arma.sourceforge.net/docs.html 100/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
abs( X )
Examples:
mat A(5, 5, fill::randu);
mat B = abs(A);
See also:
arg()
conj()
imag() / real()
conv_to()
arma.sourceforge.net/docs.html 101/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
accu( X )
Examples:
mat A(5, 6, fill::randu);
mat B(5, 6, fill::randu);
double x = accu(A);
See also:
sum()
cumsum()
trace()
mean()
dot()
as_scalar()
arma.sourceforge.net/docs.html 102/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
affmul( A, B )
The number of columns in A must be equal to number of rows in the extended form of B (ie. A.n_cols = B.n_rows+1)
Examples:
mat A(2, 3, fill::randu);
vec B(2, fill::randu);
vec C = affmul(A,B);
See also:
math operators
Affine transformation in Wikipedia
Transformation matrix in Wikipedia
arma.sourceforge.net/docs.html 103/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
all( V )
all( X )
all( X, dim )
For vector V, return true if all elements of the vector are non-zero or satisfy a relational condition
Examples:
vec V(10, fill::randu);
mat X(5, 5, fill::randu);
// status2 will be set to true if vector V has all elements greater than 0.5
bool status2 = all(V > 0.5);
// status3 will be set to true if matrix X has all elements greater than 0.6;
// note the use of vectorise()
bool status3 = all(vectorise(X) > 0.6);
// generate a row vector indicating which columns of X have all elements greater than 0.7
umat A = all(X > 0.7);
See also:
any()
approx_equal()
find()
.is_zero()
conv_to() (convert between matrix/vector types)
vectorise()
arma.sourceforge.net/docs.html 104/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
any( V )
any( X )
any( X, dim )
For vector V, return true if any element of the vector is non-zero or satisfies a relational condition
Examples:
vec V(10, fill::randu);
mat X(5, 5, fill::randu);
// status2 will be set to true if vector V has any elements greater than 0.5
bool status2 = any(V > 0.5);
// status3 will be set to true if matrix X has any elements greater than 0.6;
// note the use of vectorise()
bool status3 = any(vectorise(X) > 0.6);
// generate a row vector indicating which columns of X have elements greater than 0.7
umat A = any(X > 0.7);
See also:
all()
approx_equal()
find()
conv_to() (convert between matrix/vector types)
vectorise()
arma.sourceforge.net/docs.html 105/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
approx_equal( A, B, method, tol )
approx_equal( A, B, method, abs_tol, rel_tol )
Return false if any of the corresponding elements in A and B are not approximately equal, or if A and B have different
dimensions
The argument method controls how the approximate equality is determined; it is one of:
"absdiff" ↦ scalars x and y are considered equal if |x − y| ≤ tol
"reldiff" ↦ scalars x and y are considered equal if |x − y| / max( |x|, |y| ) ≤ tol
"both" ↦ scalars x and y are considered equal if |x − y| ≤ abs_tol or |x − y| / max( |x|, |y| ) ≤ rel_tol
Examples:
mat A(5, 5, fill::randu);
mat B = A + 0.001;
See also:
all()
any()
find()
.is_zero()
relational operators
arma.sourceforge.net/docs.html 106/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
arg( X )
Examples:
cx_mat A(5, 5, fill::randu);
mat B = arg(A);
See also:
abs()
atan2()
Argument (complex analysis) in Wikipedia
Complex Argument in MathWorld
arma.sourceforge.net/docs.html 107/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
as_scalar( expression )
Evaluate an expression that results in a 1x1 matrix, followed by converting the 1x1 matrix to a pure scalar
Optimised expression evaluations are automatically used when a binary or trinary expression is given (ie. 2 or 3 terms)
Examples:
rowvec r(5, fill::randu);
colvec q(5, fill::randu);
double a = as_scalar(r*q);
double b = as_scalar(r*X*q);
double c = as_scalar(r*diagmat(X)*q);
double d = as_scalar(r*inv(diagmat(X))*q);
See also:
.as_col() / .as_row()
vectorise()
accu()
trace()
dot()
norm()
conv_to()
arma.sourceforge.net/docs.html 108/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
clamp( X, min_val, max_val )
Create a copy of X with each element clamped to the [min_val, max_val] interval;
any value lower than min_val will be set to min_val, and any value higher than max_val will be set to max_val
For objects with complex elements, the real and imaginary components are clamped separately
Examples:
mat A(5, 5, fill::randu);
See also:
.clamp() (member function)
.min() & .max()
.clean()
.replace()
find()
arma.sourceforge.net/docs.html 109/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cond( A )
Return the condition number of matrix A (the ratio of the largest singular value to the smallest)
The ideal condition number is close to 1; large condition numbers suggest that matrix A is nearly singular
Examples:
mat A(5, 5, fill::randu);
double c = cond(A);
See also:
rcond()
rank()
inv()
solve()
condition number in MathWorld
condition number in Wikipedia
arma.sourceforge.net/docs.html 110/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
conj( X )
Examples:
cx_mat X(5, 5, fill::randu);
cx_mat Y = conj(X);
See also:
abs()
imag() / real()
trans()
arma.sourceforge.net/docs.html 111/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
conv_to< type >::from( X )
Convert (cast) from one matrix type to another (eg. mat to imat), or one cube type to another (eg. cube to icube)
Conversion of a mat object into colvec, rowvec or std::vector is possible if the object can be interpreted as a vector
Examples:
mat A(5, 5, fill::randu);
fmat B = conv_to<fmat>::from(A);
stdvec x(3);
x[0] = 0.0; x[1] = 1.0; x[2] = 2.0;
See also:
as_scalar()
abs()
imag() / real()
advanced constructors (matrices)
advanced constructors (cubes)
arma.sourceforge.net/docs.html 112/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cross( A, B )
Calculate the cross product between A and B, under the assumption that A and B are 3 dimensional vectors
Examples:
vec a(3, fill::randu);
vec b(3, fill::randu);
vec c = cross(a,b);
See also:
dot()
Cross product in Wikipedia
Cross product in MathWorld
arma.sourceforge.net/docs.html 113/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cumsum( V )
cumsum( X )
cumsum( X, dim )
For vector V, return a vector of the same orientation, containing the cumulative sum of elements
For matrix X, return a matrix containing the cumulative sum of elements in each column (dim = 0), or each row (dim = 1)
Examples:
mat A(5, 5, fill::randu);
mat B = cumsum(A);
mat C = cumsum(A, 1);
See also:
cumprod()
accu()
sum()
diff()
arma.sourceforge.net/docs.html 114/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cumprod( V )
cumprod( X )
cumprod( X, dim )
For vector V, return a vector of the same orientation, containing the cumulative product of elements
For matrix X, return a matrix containing the cumulative product of elements in each column (dim = 0), or each row (dim = 1)
Examples:
mat A(5, 5, fill::randu);
mat B = cumprod(A);
mat C = cumprod(A, 1);
See also:
cumsum()
prod()
arma.sourceforge.net/docs.html 115/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
val = det( A ) (form 1)
det( val, A ) (form 2)
form 2: store the calculated determinant in val and return a bool indicating success
Caveat: log_det() is preferred, as it's less likely to suffer from numerical underflows/overflows
Examples:
mat A(5, 5, fill::randu);
double val2;
bool success = det(val2, A); // form 2
See also:
log_det()
rcond()
determinant in MathWorld
determinant in Wikipedia
arma.sourceforge.net/docs.html 116/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
diagmat( V )
diagmat( V, k )
diagmat( X )
diagmat( X, k )
Given vector V, generate a square matrix with the k-th diagonal containing a copy of the vector; all other elements are set to
zero
Given matrix X, generate a matrix with the k-th diagonal containing a copy of the k-th diagonal of X; all other elements are
set to zero
For k > 0, the k-th super-diagonal is used (above main diagonal, towards top-right corner)
For k < 0, the k-th sub-diagonal is used (below main diagonal, towards bottom-left corner)
Examples:
mat A(5, 5, fill::randu);
mat B = diagmat(A);
mat C = diagmat(A,1);
See also:
.diag()
.is_diagmat()
diagvec()
trimatu() / trimatl()
symmatu() / symmatl()
reshape()
vectorise()
diagonal matrix in Wikipedia
arma.sourceforge.net/docs.html 117/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
diagvec( A )
diagvec( A, k )
Examples:
mat A(5, 5, fill::randu);
vec d = diagvec(A);
See also:
.diag()
diagmat()
trace()
vectorise()
arma.sourceforge.net/docs.html 118/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
diff( V )
diff( V, k )
diff( X )
diff( X, k )
diff( X, k, dim )
For vector V, return a vector of the same orientation, containing the differences between consecutive elements
For matrix X, return a matrix containing the differences between consecutive elements in each column (dim = 0), or each row
(dim = 1)
The optional argument k indicates that the differences are calculated recursively k times; by default k = 1 is used
The resulting number of differences is n − k, where n is the number of elements; if n ≤ k, the number of differences is zero (ie.
an empty vector/matrix is returned)
Examples:
vec a = linspace<vec>(1,10,10);
vec b = diff(a);
See also:
trapz()
numerical differentiation in Wikipedia
numerical differentiation in MathWorld
arma.sourceforge.net/docs.html 119/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
dot( A, B )
cdot( A, B )
norm_dot( A, B )
Caveat: norm() is more robust for calculating the norm, as it handles underflows and overflows
Examples:
vec a(10, fill::randu);
vec b(10, fill::randu);
double x = dot(a,b);
See also:
norm()
as_scalar()
cross()
conj()
arma.sourceforge.net/docs.html 120/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
eps( X )
Obtain the positive distance of the absolute value of each element of X to the next largest representable floating point
number
Examples:
mat A(4, 5, fill::randu);
mat B = eps(A);
See also:
datum::eps
Floating-Point Arithmetic in MathWorld
IEEE Standard for Floating-Point Arithmetic in Wikipedia
arma.sourceforge.net/docs.html 121/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
B = expmat( A )
expmat( B, A )
Caveat: the matrix exponential operation is generally not the same as applying the exp() function to each element
Examples:
mat A(5, 5, fill::randu);
mat B = expmat(A);
See also:
expmat_sym()
logmat()
sqrtmat()
miscellaneous element-wise functions
matrix exponential in Wikipedia
matrix exponential in MathWorld
Nineteen Dubious Ways to Compute the Exponential of a Matrix, Twenty-Five Years Later
arma.sourceforge.net/docs.html 122/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
B = expmat_sym( A )
expmat_sym( B, A )
Caveat: the matrix exponential operation is generally not the same as applying the exp() function to each element
Examples:
mat A(5, 5, fill::randu);
mat C = expmat_sym(B);
See also:
expmat()
logmat_sympd()
sqrtmat_sympd()
.is_symmetric()
.is_hermitian()
miscellaneous element-wise functions
matrix exponential in Wikipedia
matrix exponential in MathWorld
Nineteen Dubious Ways to Compute the Exponential of a Matrix, Twenty-Five Years Later
arma.sourceforge.net/docs.html 123/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
find( X )
find( X, k )
find( X, k, s )
Return a column vector containing the indices of elements of X that are non-zero or satisfy a relational condition
The output vector must have the type uvec (ie. the indices are stored as unsigned integers of type uword)
If k = 0 (default), return the indices of all non-zero elements, otherwise return at most k of their indices
If s = "first" (default), return at most the first k indices of the non-zero elements
Caveats:
to clamp values to an interval, clamp() is more efficient
to replace a specific value, .replace() is more efficient
Examples:
mat A(5, 5, fill::randu);
mat B(5, 5, fill::randu);
See also:
all()
any()
clamp()
.transform()
approx_equal()
find_finite()
find_nonfinite()
find_unique()
nonzeros()
unique()
sort_index()
ind2sub()
.index_min() & .index_max()
trimatu_ind() / trimatl_ind()
submatrix views
subcube views
arma.sourceforge.net/docs.html 124/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
find_finite( X )
Return a column vector containing the indices of elements of X that are finite (ie. not ±Inf and not NaN)
The output vector must have the type uvec (ie. the indices are stored as unsigned integers of type uword)
Examples:
mat A(5, 5, fill::randu);
A(1,1) = datum::inf;
See also:
find()
find_nonfinite()
.is_finite()
.replace()
.has_inf()
.has_nan()
submatrix views
constants (pi, nan, inf, ...)
arma.sourceforge.net/docs.html 125/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
find_nonfinite( X )
Return a column vector containing the indices of elements of X that are non-finite (ie. ±Inf or NaN)
The output vector must have the type uvec (ie. the indices are stored as unsigned integers of type uword)
Examples:
mat A(5, 5, fill::randu);
A(1,1) = datum::inf;
A(2,2) = datum::nan;
Caveat: to replace instances of a specific non-finite value (eg. nan or inf), it is more efficient to use .replace()
See also:
find()
find_finite()
.is_finite()
.replace()
.has_inf()
.has_nan()
submatrix views
constants (pi, nan, inf, ...)
arma.sourceforge.net/docs.html 126/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
find_unique( X )
find_unique( X, ascending_indices )
The output vector must have the type uvec (ie. the indices are stored as unsigned integers of type uword)
Examples:
mat A = { { 2, 2, 4 },
{ 4, 6, 6 } };
See also:
find()
unique()
intersect()
submatrix views
arma.sourceforge.net/docs.html 127/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
fliplr( X )
flipud( X )
fliplr(): generate a copy of matrix X, with the order of the columns reversed
flipud(): generate a copy of matrix X, with the order of the rows reversed
Examples:
mat A(5, 5, fill::randu);
mat B = fliplr(A);
mat C = flipud(A);
See also:
reverse()
shift()
.swap_rows() & .swap_cols()
.t()
arma.sourceforge.net/docs.html 128/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
imag( X )
real( X )
Examples:
cx_mat C(5, 5, fill::randu);
mat A = imag(C);
mat B = real(C);
See also:
.set_imag() / .set_real()
abs()
conj()
conv_to()
arma.sourceforge.net/docs.html 129/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
uvec sub = ind2sub( size(X), index ) (form 1)
umat sub = ind2sub( size(X), vector_of_indices ) (form 2)
The argument size(X) can be replaced with size(n_rows, n_cols) or size(n_rows, n_cols, n_slices)
When only one index is given (form 1), the subscripts are returned in a vector of type uvec
When a vector of indices (of type uvec) is given (form 2), the corresponding subscripts are returned in each column of an m x n
matrix of type umat; m=2 for matrix subscripts, while m=3 for cube subscripts
Examples:
mat M(4, 5, fill::randu);
cube Q(2,3,4);
See also:
size()
sub2ind()
element access
find()
arma.sourceforge.net/docs.html 130/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
index_min( V) index_max( V)
index_min( M) index_max( M)
index_min( M, dim ) index_max( M, dim )
index_min( Q) index_max( Q)
index_min( Q, dim ) index_max( Q, dim )
For vector V, return the linear index of the extremum value; the returned index is of type uword
For cube Q, return a cube (of type ucube) containing the indices of extremum values of elements along dimension dim, where
dim ∈ { 0, 1, 2 }
For objects with complex numbers, absolute values are used for comparison
Examples:
vec v(10, fill::randu);
uword i = index_max(v);
double max_val_in_v = v(i);
urowvec ii = index_max(M);
ucolvec jj = index_max(M,1);
See also:
min() & max()
.index_min() & .index_max() (member functions)
sort_index()
find()
arma.sourceforge.net/docs.html 131/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
inplace_trans( X )
inplace_trans( X, method )
inplace_strans( X )
inplace_strans( X, method )
By default, a greedy transposition algorithm is used; a low-memory algorithm can be used instead by explicitly setting method
to "lowmem"
The low-memory algorithm is considerably slower than the greedy algorithm; using the low-memory algorithm is only
recommended for cases where X takes up more than half of available memory (ie. very large X)
Examples:
mat X(4, 5, fill::randu);
mat Y(20000, 30000, fill::randu);
See also:
.t()
trans()
inplace matrix transpose in Wikipedia
arma.sourceforge.net/docs.html 132/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
C = intersect( A, B ) (form 1)
intersect( C, iA, iB, A, B ) (form 2)
For form 1:
return the unique elements common to both A and B, sorted in ascending order
For form 2:
store in C the unique elements common to both A and B, sorted in ascending order
store in iA and iB the indices of the unique elements, such that C = A.elem(iA) and C = B.elem(iB)
iA and iB must have the type uvec (ie. the indices are stored as unsigned integers of type uword)
C is a column vector if either A or B is a matrix or column vector; C is a row vector if both A and B are row vectors
For matrices and vectors with complex numbers, ordering is via absolute values
Examples:
ivec A = regspace<ivec>(4, 1); // 4, 3, 2, 1
ivec B = regspace<ivec>(3, 6); // 3, 4, 5, 6
ivec C = intersect(A,B); // 3, 4
ivec CC;
uvec iA;
uvec iB;
See also:
unique()
find_unique()
submatrix views
arma.sourceforge.net/docs.html 133/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
join_rows( A, B ) join_horiz( A, B )
join_rows( A, B, C ) join_horiz( A, B, C )
join_rows( A, B, C, D ) join_horiz( A, B, C, D )
join_cols( A, B ) join_vert( A, B )
join_cols( A, B, C ) join_vert( A, B, C )
join_cols( A, B, C, D ) join_vert( A, B, C, D )
join_rows() and join_horiz(): horizontal concatenation; join the corresponding rows of the given matrices; the given matrices
must have the same number of rows
join_cols() and join_vert(): vertical concatenation; join the corresponding columns of the given matrices; the given matrices
must have the same number of columns
Examples:
mat A(4, 5, fill::randu);
mat B(4, 6, fill::randu);
mat C(6, 5, fill::randu);
mat AB = join_rows(A,B);
mat AC = join_cols(A,C);
See also:
.shed_rows/cols/slices
.insert_rows/cols/slices
submatrix views
arma.sourceforge.net/docs.html 134/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
join_slices( cube C, cube D )
join_slices( mat M, mat N )
for two cubes C and D: join the slices of C with the slices of D; cubes C and D must have the same number of rows and columns
(ie. all slices must have the same size)
for two matrices M and N: treat M and N as cube slices and join them to form a cube with 2 slices; matrices M and N must
have the same number of rows and columns
for matrix M and cube C: treat M as a cube slice and join it with the slices of C; matrix M and cube C must have the same
number of rows and columns
Examples:
cube C(5, 10, 3, fill::randu);
cube D(5, 10, 4, fill::randu);
cube E = join_slices(C,D);
cube Q = join_slices(M,N);
cube R = join_slices(Q,M);
cube S = join_slices(M,Q);
See also:
.shed_rows/cols/slices
.insert_rows/cols/slices
subcube views
arma.sourceforge.net/docs.html 135/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
kron( A, B )
Given matrix A (with n rows and p columns) and matrix B (with m rows and q columns), generate a matrix (with nm rows and
pq columns) that denotes the tensor product of A and B
Examples:
mat A(4, 5, fill::randu);
mat B(5, 4, fill::randu);
mat K = kron(A,B);
See also:
repmat()
repelem()
Kronecker product in MathWorld
Kronecker product in Wikipedia
arma.sourceforge.net/docs.html 136/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
complex result = log_det( A ) (form 1)
log_det( val, sign, A ) (form 2)
form 2: store the calculated log determinant in val and sign, and return a bool indicating success;
the determinant is equal to exp(val) · sign
Examples:
mat A(5, 5, fill::randu);
double val;
double sign;
See also:
log_det_sympd()
det()
rcond()
cx_double
determinant in MathWorld
determinant in Wikipedia
arma.sourceforge.net/docs.html 137/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
result = log_det_sympd( A ) (form 1)
log_det_sympd( result, A ) (form 2)
form 2: store the calculated log determinant in result and return a bool indicating success
Examples:
mat A(5, 5, fill::randu);
double result2;
bool success = log_det_sympd(result2, B); // form 2
See also:
log_det()
rcond()
determinant in MathWorld
determinant in Wikipedia
arma.sourceforge.net/docs.html 138/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
B = logmat( A )
logmat( B, A )
Caveat: the matrix logarithm operation is generally not the same as applying the log() function to each element
Examples:
mat A(5, 5, fill::randu);
cx_mat B = logmat(A);
See also:
logmat_sympd()
expmat()
sqrtmat()
real()
miscellaneous element-wise functions
matrix logarithm in Wikipedia
arma.sourceforge.net/docs.html 139/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
B = logmat_sympd( A )
logmat_sympd( B, A )
Caveat: the matrix logarithm operation is generally not the same as applying the log() function to each element
Examples:
mat A(5, 5, fill::randu);
mat C = logmat_sympd(B);
See also:
logmat()
expmat_sym()
sqrtmat_sympd()
.is_sympd()
miscellaneous element-wise functions
matrix logarithm in Wikipedia
positive definite matrix in Wikipedia
positive definite matrix in MathWorld
arma.sourceforge.net/docs.html 140/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
min( V) max( V)
min( M) max( M)
min( M, dim ) max( M, dim )
min( Q) max( Q)
min( Q, dim ) max( Q, dim )
min( A, B ) max( A, B )
For matrix M, return the extremum value for each column (dim = 0), or each row (dim = 1)
For cube Q, return the extremum values of elements along dimension dim, where dim ∈ { 0, 1, 2 }
For two matrices/cubes A and B, return a matrix/cube containing element-wise extremum values
For objects with complex numbers, absolute values are used for comparison
Examples:
colvec v(10, fill::randu);
double x = max(v);
rowvec a = max(M);
rowvec b = max(M,0);
colvec c = max(M,1);
// element-wise maximum
mat X(5, 6, fill::randu);
mat Y(5, 6, fill::randu);
mat Z = arma::max(X,Y); // use arma:: prefix to distinguish from std::max()
See also:
.min() & .max() (member functions)
index_min() & index_max()
clamp()
statistics functions
running_stat - class for running statistics of scalars
running_stat_vec - class for running statistics of vectors
ensmallen - library for finding minimum of arbitrary function
arma.sourceforge.net/docs.html 141/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
nonzeros( X )
Caveats:
for dense matrices/vectors, to obtain the number of non-zero elements, the expression accu(X != 0) is more efficient
for sparse matrices, to obtain the number of non-zero elements, the .n_nonzero attribute is more efficient, eg.
X.n_nonzero
Examples:
sp_mat A = sprandu<sp_mat>(100, 100, 0.1);
vec a = nonzeros(A);
See also:
find()
unique()
vectorise()
.clean()
.for_each()
arma.sourceforge.net/docs.html 142/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
norm( X )
norm( X, p )
For matrices, p is one of: 1, 2, "inf", "fro"; the calculated norm is the induced norm (not entrywise norm)
"-inf" is the minimum norm, "inf" is the maximum norm, "fro" is the Frobenius norm
For vector norm with p = 2 and matrix norm with p = "fro", a robust algorithm is used to reduce the likelihood of underflows
and overflows
To obtain the zero/Hamming pseudo-norm (the number of non-zero elements), use this expression: accu(X != 0)
Examples:
vec q(5, fill::randu);
See also:
normalise()
vectorise()
dot()
vector norm in Wikipedia
vector norm in MathWorld
matrix norm in Wikipedia
matrix norm in MathWorld
arma.sourceforge.net/docs.html 143/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
normalise( V )
normalise( V, p )
normalise( X )
normalise( X, p )
normalise( X, p, dim )
For vector V, return its normalised version (ie. having unit p-norm)
For matrix X, return its normalised version, where each column (dim = 0) or row (dim = 1) has been normalised to have unit p-
norm
Examples:
vec A(10, fill::randu);
vec B = normalise(A);
vec C = normalise(A, 1);
See also:
norm()
norm_dot()
Normalised vector in MathWorld
Unit vector in Wikipedia
arma.sourceforge.net/docs.html 144/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
prod( V )
prod( M )
prod( M, dim )
For matrix M, return the product of elements in each column (dim = 0), or each row (dim = 1)
Examples:
colvec v(10, fill::randu);
double x = prod(v);
rowvec a = prod(M);
rowvec b = prod(M,0);
colvec c = prod(M,1);
See also:
cumprod()
Schur product
arma.sourceforge.net/docs.html 145/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
B = powmat( A, n )
powmat( B, A, n )
Matrix power operation: raise square matrix A to the power of n, where n has the type int or double
If n has the type double, the resultant matrix B always has complex elements
Caveats:
to find the inverse of a matrix, use inv() instead
to solve a system of linear equations, use solve() instead
to find the matrix square root, use sqrtmat() instead
the matrix power operation is generally not the same as applying the pow() function to each element
Examples:
mat A(5, 5, fill::randu);
See also:
sqrtmat()
inv()
eye()
operators
miscellaneous element-wise functions
arma.sourceforge.net/docs.html 146/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
r = rank( X ) (form 1)
r = rank( X, tolerance )
rank( r, X ) (form 2)
rank( r, X, tolerance )
form 2: store the calculated rank in r and return a bool indicating success
The tolerance argument is optional; by default tolerance is set to max_rc · max_sv · epsilon, where:
max_rc = max(X.n_rows, X.n_cols)
max_sv = maximum singular value of X
epsilon = difference between 1 and the least value greater than 1 that is representable
Caveat: to distinguish from std::rank, use the arma:: prefix, ie. arma::rank(X)
Examples:
mat A(4, 5, fill::randu);
uword r2;
bool success = rank(r2, A); // form 2
See also:
rcond()
svd()
orth()
datum::eps
Rank in MathWorld
Rank in Wikipedia
arma.sourceforge.net/docs.html 147/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
rcond( A )
Return the 1-norm estimate of the reciprocal condition number of square matrix A
Examples:
mat A(5, 5, fill::randu);
double r = rcond(A);
See also:
cond()
rank()
det()
inv()
solve()
arma.sourceforge.net/docs.html 148/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
repelem( A, num_copies_per_row, num_copies_per_col )
Examples:
mat A(2, 3, fill::randu);
See also:
repmat()
kron()
reshape()
resize()
arma.sourceforge.net/docs.html 149/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
repmat( A, num_copies_per_row, num_copies_per_col )
Caveat: to apply a vector operation on each row or column of a matrix, it is generally more efficient to use .each_row() or
.each_col()
Examples:
mat A(2, 3, fill::randu);
See also:
.each_col() & .each_row() (vector operations applied to each column or row)
repelem()
kron()
reshape()
resize()
arma.sourceforge.net/docs.html 150/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
reshape( X, n_rows, n_cols ) (X is a vector or matrix)
reshape( X, size(Y) )
Generate a vector/matrix/cube with given size specifications, whose elements are taken from the given object in a column-
wise manner; the elements in the generated object are placed column-wise (ie. the first column is filled up before filling the
second column)
The layout of the elements in the generated object will be different to the layout in the given object
If the total number of elements in the given object is less than the specified size, the remaining elements in the generated
object are set to zero
If the total number of elements in the given object is greater than the specified size, only a subset of elements is taken from
the given object
Caveats:
do not use reshape() to change the size without preserving data; use .set_size() instead, which is much faster
to grow/shrink a matrix while preserving the elements as well as the layout of the elements, use resize() instead
to flatten a matrix into a vector, use vectorise() or .as_col() / .as_row() instead
Examples:
mat A(10, 5, fill::randu);
See also:
.reshape() (member function)
.set_size()
resize()
vectorise()
as_scalar()
conv_to()
diagmat()
repmat()
repelem()
size()
interp2()
arma.sourceforge.net/docs.html 151/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
resize( X, n_rows, n_cols ) (X is a vector or matrix)
resize( X, size(Y) )
Generate a vector/matrix/cube with given size specifications, whose elements as well as the layout of the elements are taken
from the given object
Caveat: do not use resize() to change the size without preserving data; use .set_size() instead, which is much faster
Examples:
mat A(4, 5, fill::randu);
See also:
.resize() (member function of Mat and Cube)
.set_size() (member function of Mat and Cube)
reshape()
vectorise()
as_scalar()
conv_to()
repmat()
repelem()
size()
arma.sourceforge.net/docs.html 152/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
reverse( V )
reverse( X )
reverse( X, dim )
For vector V, generate a copy of the vector with the order of elements reversed
For matrix X, generate a copy of the matrix with the order of elements reversed in each column (dim = 0), or each row (dim =
1)
Examples:
vec v(123, fill::randu);
vec y = reverse(v);
See also:
fliplr() & flipud()
shift()
sort()
trans()
.t()
.swap_rows() & .swap_cols()
arma.sourceforge.net/docs.html 153/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
R = roots( P )
roots( R, P )
Find the complex roots of a polynomial function represented via vector P and store them in column vector R
Examples:
vec P(5, fill::randu);
cx_vec R = roots(P);
See also:
polyval()
polyfit()
real()
solve()
zero of a function in Wikipedia
arma.sourceforge.net/docs.html 154/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
shift( V, N )
shift( X, N )
shift( X, N, dim )
For vector V, generate a copy of the vector with the elements shifted by N positions in a circular manner
For matrix X, generate a copy of the matrix with the elements shifted by N positions in each column (dim = 0), or each row
(dim = 1)
Examples:
mat A(4, 5, fill::randu);
mat B = shift(A, -1);
mat C = shift(A, +1);
See also:
shuffle()
fliplr() & flipud()
reverse()
arma.sourceforge.net/docs.html 155/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
shuffle( V )
shuffle( X )
shuffle( X, dim )
For vector V, generate a copy of the vector with the elements shuffled
For matrix X, generate a copy of the matrix with the elements shuffled in each column (dim = 0), or each row (dim = 1)
Examples:
mat A(4, 5, fill::randu);
mat B = shuffle(A);
See also:
shift()
sort()
unique()
randi()
arma.sourceforge.net/docs.html 156/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
size( X )
size( n_rows, n_cols )
size( n_rows, n_cols, n_slices )
The dimensions support simple arithmetic operations; they can also be printed and compared for equality/inequality
Caveat: to prevent interference from std::size() in C++17, preface Armadillo's size() with the arma namespace qualification,
eg. arma::size(X)
Examples:
mat A(5,6);
mat C; C.randu(size(A));
mat D = ones<mat>(size(A));
mat G( size(A) * 2 );
See also:
attributes
arma.sourceforge.net/docs.html 157/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
sort( V )
sort( V, sort_direction )
sort( X )
sort( X, sort_direction )
sort( X, sort_direction, dim )
For vector V, return a vector which is a sorted version of the input vector
For matrix X, return a matrix with the elements of the input matrix sorted in each column (dim = 0), or each row (dim = 1)
The sort_direction argument is optional; sort_direction is either "ascend" or "descend"; by default "ascend" is used
For matrices and vectors with complex numbers, sorting is via absolute values
Examples:
mat A(10, 10, fill::randu);
mat B = sort(A);
See also:
sort_index()
.is_sorted()
shuffle()
unique()
reverse()
randi()
arma.sourceforge.net/docs.html 158/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
sort_index( X )
sort_index( X, sort_direction )
stable_sort_index( X )
stable_sort_index( X, sort_direction )
Return a vector which describes the sorted order of the elements of X (ie. it contains the indices of the elements of X)
The output vector must have the type uvec (ie. the indices are stored as unsigned integers of type uword)
The sort_direction argument is optional; sort_direction is either "ascend" or "descend"; by default "ascend" is used
The stable_sort_index() variant preserves the relative order of elements with equivalent values
For matrices and vectors with complex numbers, sorting is via absolute values
Examples:
vec q(10, fill::randu);
See also:
sort()
find()
.is_sorted()
.index_min() & .index_max()
ind2sub()
arma.sourceforge.net/docs.html 159/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
B = sqrtmat( A )
sqrtmat( B, A )
If matrix A appears to be singular, an approximate square root is attempted; additionally, sqrtmat(B,A) returns a bool set to
false
Caveat: the square root of a matrix is generally not the same as applying the sqrt() function to each element
Examples:
mat A(5, 5, fill::randu);
cx_mat B = sqrtmat(A);
See also:
sqrtmat_sympd()
powmat()
expmat()
logmat()
chol()
real()
miscellaneous element-wise functions
square root of a matrix in Wikipedia
arma.sourceforge.net/docs.html 160/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
B = sqrtmat_sympd( A )
sqrtmat_sympd( B, A )
Caveat: the matrix square root operation is generally not the same as applying the sqrt() function to each element
Examples:
mat A(5, 5, fill::randu);
mat C = sqrtmat_sympd(B);
See also:
sqrtmat()
expmat_sym()
logmat_sympd()
chol()
.is_sympd()
miscellaneous element-wise functions
square root of a matrix in Wikipedia
positive definite matrix in Wikipedia
positive definite matrix in MathWorld
arma.sourceforge.net/docs.html 161/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
sum( V)
sum( M)
sum( M, dim )
sum( Q)
sum( Q, dim )
For matrix M, return the sum of elements in each column (dim = 0), or each row (dim = 1)
For cube Q, return the sums of elements along dimension dim, where dim ∈ { 0, 1, 2 }; for example, dim = 0 indicates the sum
of elements in each column within each slice
Caveat: to get a sum of all the elements regardless of the object type (ie. vector, or matrix, or cube), use accu() instead
Examples:
colvec v(10, fill::randu);
double x = sum(v);
rowvec a = sum(M);
rowvec b = sum(M,0);
colvec c = sum(M,1);
See also:
accu()
cumsum()
trace()
trapz()
mean()
as_scalar()
arma.sourceforge.net/docs.html 162/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
uword index = sub2ind( size(M), row, col ) (M is a matrix)
uvec indices = sub2ind( size(M), matrix_of_subscripts )
The argument size(X) can be replaced with size(n_rows, n_cols) or size(n_rows, n_cols, n_slices)
For the matrix_of_subscripts argument, the subscripts must be stored in each column of an m x n matrix of type umat; m = 2
for matrix subscripts, while m = 3 for cube subscripts
Examples:
mat M(4,5);
cube Q(4,5,6);
See also:
size()
ind2sub()
element access
arma.sourceforge.net/docs.html 163/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
symmatu( A )
symmatu( A, do_conj )
symmatl( A )
symmatl( A, do_conj )
symmatu(A): generate symmetric matrix from square matrix A, by reflecting the upper triangle to the lower triangle
symmatl(A): generate symmetric matrix from square matrix A, by reflecting the lower triangle to the upper triangle
If A is a complex matrix, the reflection uses the complex conjugate of the elements; to disable the complex conjugate, set
do_conj to false
Examples:
mat A(5, 5, fill::randu);
mat B = symmatu(A);
mat C = symmatl(A);
See also:
diagmat()
trimatu() / trimatl()
.is_symmetric()
.is_hermitian()
Symmetric matrix in Wikipedia
arma.sourceforge.net/docs.html 164/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
trace( X )
If X is an expression, the function aims to use optimised expression evaluations to calculate only the diagonal elements
Examples:
mat A(5, 5, fill::randu);
double x = trace(A);
See also:
accu()
as_scalar()
.diag()
diagvec()
sum()
arma.sourceforge.net/docs.html 165/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
trans( A )
strans( A )
Examples:
mat A(5, 10, fill::randu);
mat B = trans(A);
mat C = A.t(); // equivalent to trans(A), but more compact
See also:
.t()
inplace_trans()
reverse()
transpose in Wikipedia
transpose in MathWorld
conjugate transpose in Wikipedia
conjugate transpose in MathWorld
arma.sourceforge.net/docs.html 166/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
trapz( X, Y )
trapz( X, Y, dim )
trapz( Y )
trapz( Y, dim )
Compute the trapezoidal integral of Y with respect to spacing in X, in each column (dim = 0) or each row (dim = 1) of Y
X must be a vector; its length must equal either the number of rows in Y (when dim = 0), or the number of columns in Y (when
dim = 1)
Examples:
vec X = linspace<vec>(0, datum::pi, 1000);
vec Y = sin(X);
mat Z = trapz(X,Y);
See also:
diff()
sum()
linspace()
numerical integration in Wikipedia
numerical integration in MathWorld
trapezoidal rule in Wikipedia
arma.sourceforge.net/docs.html 167/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
trimatu( A )
trimatu( A, k )
trimatl( A )
trimatl( A, k )
Create a new matrix by copying either the upper or lower triangular part from square matrix A, and setting the remaining
elements to zero
trimatu() copies the upper triangular part
trimatl() copies the lower triangular part
The argument k specifies the diagonal which inclusively delineates the boundary of the triangular part
for k > 0, the k-th super-diagonal is used (above main diagonal, towards top-right corner)
for k < 0, the k-th sub-diagonal is used (below main diagonal, towards bottom-left corner)
Examples:
mat A(5, 5, fill::randu);
mat U = trimatu(A);
mat L = trimatl(A);
See also:
.is_trimatu() / .is_trimatl()
trimatu_ind() / trimatl_ind()
symmatu() / symmatl()
diagmat()
nonzeros()
Triangular matrix in MathWorld
Triangular matrix in Wikipedia
arma.sourceforge.net/docs.html 168/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
trimatu_ind( size(A) )
trimatu_ind( size(A), k )
trimatl_ind( size(A) )
trimatl_ind( size(A), k )
Return a column vector containing the indices of elements that form the upper or lower triangle part of matrix A
trimatu_ind() refers to the upper triangular part
trimatl_ind() refers to the lower triangular part
The output vector must have the type uvec (ie. the indices are stored as unsigned integers of type uword)
The argument k specifies the diagonal which inclusively delineates the boundary of the triangular part
for k > 0, the k-th super-diagonal is used (above main diagonal, towards top-right corner)
for k < 0, the k-th sub-diagonal is used (below main diagonal, towards bottom-left corner)
Examples:
mat A(5, 5, fill::randu);
See also:
trimatu() / trimatl()
find()
submatrix views
arma.sourceforge.net/docs.html 169/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
unique( A )
If A is a vector, the output is also a vector with the same orientation (row or column) as A; if A is a matrix, the output is
always a column vector
Examples:
mat X = { { 1, 2 }
{ 2, 3 } };
mat Y = unique(X);
See also:
find()
find_unique()
sort()
shuffle()
nonzeros()
intersect()
arma.sourceforge.net/docs.html 170/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
vectorise( X )
vectorise( X, dim )
vectorise( Q )
For dim = 0, the elements are copied from X column-wise, resulting in a column vector; equivalent to concatenating all the
columns of X
For dim = 1, the elements are copied from X row-wise, resulting in a row vector; equivalent to concatenating all the rows of X
Caveats:
column-wise vectorisation is faster than row-wise vectorisation
for sparse matrices, row-wise vectorisation is not recommended
Examples:
mat X(4, 5, fill::randu);
vec v = vectorise(X);
See also:
.as_col() / .as_row()
nonzeros()
reshape()
resize()
diagvec()
as_scalar()
arma.sourceforge.net/docs.html 171/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
miscellaneous element-wise functions:
Usage:
B = fn(A), where fn(A) is one of the functions below
A and B must have the same matrix type or cube type, such as mat or cube
Caveats:
all of the above functions are applied element-wise, where each element is treated independently
the element-wise functions exp(), log(), sqrt() and pow() have the corresponding functions expmat(), logmat(), sqrtmat()
and powmat() which take into account matrix structure
Examples:
mat A(5, 5, fill::randu);
mat B = exp(A);
See also:
abs()
clamp()
conj()
imag() / real()
.transform() (apply user-defined function to each element)
expmat()
logmat()
sqrtmat()
powmat()
trigonometric functions
statistics functions
miscellaneous constants
arma.sourceforge.net/docs.html 172/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
trigonometric element-wise functions (cos, sin, tan, ...)
For single argument functions, B = trig_fn(A), where trig_fn is applied to each element in A, with trig_fn as one of:
cos, acos, cosh, acosh
sin, asin, sinh, asinh
tan, atan, tanh, atanh
sinc, defined as sinc(x) = sin(πx) / (πx) for x ≠ 0, and sinc(x) = 1 for x = 0
For dual argument functions, apply the function to each tuple of two corresponding elements in X and Y:
Z = atan2(Y, X)
Z = hypot(X, Y)
Examples:
mat X(5, 5, fill::randu);
mat Y = cos(X);
See also:
miscellaneous element-wise functions
trigonometric functions in Wikipedia
atan2 function in Wikipedia
hypot function in Wikipedia
sinc function in Wikipedia
arma.sourceforge.net/docs.html 173/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
arma.sourceforge.net/docs.html 174/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
R = chol( X ) (form 1)
R = chol( X, layout ) (form 2)
chol( R, X ) (form 3)
chol( R, X, layout ) (form 4)
Cholesky decomposition of symmetric/hermitian matrix X into triangular matrix R, with an optional permutation vector/matrix
P
The optional argument layout is either "upper" or "lower", which specifies whether R is upper or lower triangular
Forms 5 to 6 require X to be positive semi-definite; these forms use pivoted decomposition and provide a permutation
vector/matrix P with type uvec or umat
Examples:
mat A(5, 5, fill::randu);
mat X = A.t()*A;
mat R1 = chol(X);
mat R2 = chol(X, "lower");
mat R3;
bool ok = chol(R3, X);
mat R;
uvec P_vec;
umat P_mat;
See also:
sqrtmat()
lu()
qr()
.is_sympd()
Cholesky decomposition in MathWorld
Cholesky decomposition in Wikipedia
Definite matrix in Wikipedia
arma.sourceforge.net/docs.html 175/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
vec eigval = eig_sym( X )
eig_sym( eigval, X )
The eigenvalues and corresponding eigenvectors are stored in eigval and eigvec, respectively
Examples:
// for matrices with real elements
vec eigval;
mat eigvec;
vec eigval2;
cx_mat eigvec2;
See also:
eig_gen()
eig_pair()
svd()
svd_econ()
princomp()
eigs_sym()
.is_symmetric()
.is_hermitian()
eigen decomposition in MathWorld
eigenvalues & eigenvectors in Wikipedia
divide & conquer eigenvalue algorithm in Wikipedia
arma.sourceforge.net/docs.html 176/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cx_vec eigval = eig_gen( X )
cx_vec eigval = eig_gen( X, bal )
eig_gen( eigval, X )
eig_gen( eigval, X, bal )
The eigenvalues and corresponding right eigenvectors are stored in eigval and eigvec, respectively
If both left and right eigenvectors are requested they are stored in leigvec and reigvec, respectively
Examples:
mat A(10, 10, fill::randu);
cx_vec eigval;
cx_mat eigvec;
See also:
eig_pair()
eig_sym()
svd()
svd_econ()
schur()
eigs_gen()
eigen decomposition in MathWorld
eigenvalues & eigenvectors in Wikipedia
arma.sourceforge.net/docs.html 177/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cx_vec eigval = eig_pair( A, B )
eig_pair( eigval, A, B )
Eigen decomposition for pair of general dense square matrices A and B of the same size, such that A*eigvec =
B*eigvec*diagmat(eigval)
The eigenvalues and corresponding right eigenvectors are stored in eigval and eigvec, respectively
If both left and right eigenvectors are requested they are stored in leigvec and reigvec, respectively
Examples:
mat A(10, 10, fill::randu);
mat B(10, 10, fill::randu);
cx_vec eigval;
cx_mat eigvec;
See also:
eig_gen()
eig_sym()
qz()
eigen decomposition in MathWorld
eigenvalues & eigenvectors in Wikipedia
arma.sourceforge.net/docs.html 178/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
H = hess( X )
hess( H, X )
hess( U, H, X )
H is a square matrix known as the upper Hessenberg matrix, with elements below the first subdiagonal set to zero
Examples:
mat X(20,20, fill::randu);
mat U;
mat H;
hess(U, H, X);
See also:
qz()
schur()
Hessenberg decomposition in MathWorld
Hessenberg matrix in Wikipedia
arma.sourceforge.net/docs.html 179/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
B = inv( A )
B = inv( A, settings )
inv( B, A )
inv( B, A, settings )
inv( B, rcond, A )
inv_opts::no_ugly do not provide inverses for poorly conditioned matrices (where rcond < datum::eps)
provide approximate inverses for rank deficient or poorly conditioned matrices; similar to pseudo-
inv_opts::allow_approx
inverse
inv_opts::tiny use fast inverse algorithm for tiny matrices (with size ≤ 4x4); may produce lower quality inverses
If A appears to be singular:
B = inv(A) resets B and throws a std::runtime_error exception
inv(B,A) resets B and returns a bool set to false (exception is not thrown)
inv(B,rcond,A) resets B, sets rcond to zero, and returns a bool set to false (exception is not thrown)
Caveats:
if matrix A is know to be symmetric positive definite, using inv_sympd() is faster
if matrix A is know to be diagonal, use inv( diagmat(A) )
if matrix A is know to be triangular, use inv( trimatu(A) ) or inv( trimatl(A) )
to solve a system of linear equations, such as Z = inv(X)*Y, using solve() can be faster and/or more accurate
Examples:
mat A(5, 5, fill::randu);
mat B = inv(A);
mat C;
bool success = inv(C, A);
mat D;
double rcond_val;
inv(D, rcond_val, A);
A.col(1).zeros();
mat E;
inv(E, A, inv_opts::allow_approx);
See also:
.i()
inv_sympd()
rcond()
pinv()
solve()
spsolve()
diagmat()
trimatu() / trimatl()
powmat()
matrix inverse in MathWorld
invertible matrix in Wikipedia
arma.sourceforge.net/docs.html 180/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
B = inv_sympd( A )
B = inv_sympd( A, settings )
inv_sympd( B, A )
inv_sympd( B, A, settings )
inv_sympd( B, rcond, A )
inv_opts::no_ugly do not provide inverses for poorly conditioned matrices (where rcond < datum::eps)
provide approximate inverses for rank deficient or poorly conditioned symmetric matrices; similar to
inv_opts::allow_approx
pseudo-inverse
inv_opts::tiny use fast inverse algorithm for tiny matrices (with size ≤ 4x4); may produce lower quality inverses
Caveat: to solve a system of linear equations, such as Z = inv(X)*Y, using solve() can be faster and/or more accurate
Examples:
mat A(5, 5, fill::randu);
mat B = A.t() * A;
mat C = inv_sympd(B);
mat D;
bool success = inv_sympd(D, B);
mat E;
double rcond_val;
inv_sympd(E, rcond_val, B);
B.col(1).zeros();
B.row(1).zeros();
mat F;
inv_sympd(F, B, inv_opts::allow_approx);
See also:
inv()
rcond()
pinv()
solve()
eig_sym()
.is_sympd()
matrix inverse in MathWorld
invertible matrix in Wikipedia
positive definite matrix in MathWorld
positive definite matrix in Wikipedia
arma.sourceforge.net/docs.html 181/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
lu( L, U, P, X )
lu( L, U, X )
The first form provides a lower-triangular matrix L, an upper-triangular matrix U, and a permutation matrix P, such that
P.t()*L*U = X
The second form provides permuted L and U, such that L*U = X; note that in this case L is generally not lower-triangular
Examples:
mat A(5, 5, fill::randu);
mat L, U, P;
lu(L, U, P, A);
mat B = P.t()*L*U;
See also:
chol()
LU decomposition in Wikipedia
LU decomposition in MathWorld
arma.sourceforge.net/docs.html 182/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
B = null( A )
B = null( A, tolerance )
null( B, A )
null( B, A, tolerance )
The dimension of the range space is the number of singular values of A not greater than tolerance
The tolerance argument is optional; by default tolerance is set to max_rc · max_sv · epsilon, where:
mar_rc = max(A.n_rows, A.n_cols)
max_sv = maximum singular value of A
epsilon = difference between 1 and the least value greater than 1 that is representable
Examples:
mat A(5, 6, fill::randu);
A.row(0).zeros();
A.col(0).zeros();
mat B = null(A);
See also:
orth()
qr()
svd()
rank()
datum::eps
Orthonormal basis in Wikipedia
arma.sourceforge.net/docs.html 183/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
B = orth( A )
B = orth( A, tolerance )
orth( B, A )
orth( B, A, tolerance )
Find the orthonormal basis of the range space of matrix A, so that B.t()*B ≈ eye(r,r), where r = rank(A)
The dimension of the range space is the number of singular values of A greater than tolerance
The tolerance argument is optional; by default tolerance is set to max_rc · max_sv · epsilon, where:
mar_rc = max(A.n_rows, A.n_cols)
max_sv = maximum singular value of A
epsilon = difference between 1 and the least value greater than 1 that is representable
Examples:
mat A(5, 6, fill::randu);
mat B = orth(A);
See also:
null()
qr()
svd()
rank()
datum::eps
Orthonormal basis in Wikipedia
arma.sourceforge.net/docs.html 184/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
B = pinv( A )
B = pinv( A, tolerance )
B = pinv( A, tolerance, method )
pinv( B, A )
pinv( B, A, tolerance )
pinv( B, A, tolerance, method )
Caveat: to find approximate solutions (eg. minimum norm, least squares) to underdetermined, overdetermined, or rank
deficient systems of linear equations, using solve() can be considerably faster and/or more accurate
Examples:
mat A(4, 5, fill::randu);
See also:
.i()
inv()
solve()
spsolve()
datum::eps
Pseudoinverse in MathWorld
Moore-Penrose Matrix Inverse in MathWorld
Moore-Penrose inverse in Wikipedia
arma.sourceforge.net/docs.html 185/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
qr( Q, R, X ) (form 1)
qr( Q, R, P, X, "vector" ) (form 2)
qr( Q, R, P, X, "matrix" ) (form 3)
Decomposition of X into an orthogonal matrix Q and a right triangular matrix R, with an optional permutation matrix/vector P
form 1: decomposition has the form Q*R = X
form 2: P is permutation vector with type uvec; decomposition has the form Q*R = X.cols(P)
form 3: P is permutation matrix with type umat; decomposition has the form Q*R = X*P
If P is specified, a column pivoting decomposition is used; the diagonal entries of R are ordered from largest to smallest
magnitude
If the decomposition fails, Q, R and P are reset and the function returns a bool set to false (exception is not thrown)
Examples:
mat X(5, 5, fill::randu);
mat Q;
mat R;
qr(Q, R, X);
uvec P_vec;
umat P_mat;
See also:
qr_econ()
chol()
orth()
orthogonal matrix in Wikipedia
QR decomposition in Wikipedia
QR decomposition in MathWorld
arma.sourceforge.net/docs.html 186/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
qr_econ( Q, R, X )
Economical decomposition of X (with size m x n) into an orthogonal matrix Q and a right triangular matrix R, such that Q*R = X
If m > n, only the first n rows of R and the first n columns of Q are calculated (ie. the zero rows of R and the corresponding
columns of Q are omitted)
If the decomposition fails, Q and R are reset and the function returns a bool set to false (exception is not thrown)
Examples:
mat X(6, 5, fill::randu);
mat Q;
mat R;
qr_econ(Q, R, X);
See also:
qr()
orthogonal matrix in Wikipedia
QR decomposition in Wikipedia
QR decomposition in Octave
QR decomposition in MathWorld
arma.sourceforge.net/docs.html 187/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
qz( AA, BB, Q, Z, A, B )
qz( AA, BB, Q, Z, A, B, select )
Generalised Schur decomposition for pair of general square matrices A and B of the same size,
such that A = Q.t()*AA*Z.t() and B = Q.t()*BB*Z.t()
The select argument is optional and specifies the ordering of the top left of the Schur form; it is one of the following:
"none" no ordering (default operation)
"lhp" left-half-plane: eigenvalues with real part < 0
"rhp" right-half-plane: eigenvalues with real part > 0
"iuc" inside-unit-circle: eigenvalues with absolute value < 1
"ouc" outside-unit-circle: eigenvalues with absolute value > 1
The left and right Schur vectors are stored in Q and Z, respectively
In the complex-valued problem, the generalised eigenvalues are found in diagvec(AA) / diagvec(BB)
If the decomposition fails, AA, BB, Q and Z are reset, and the function returns a bool set to false (exception is not thrown)
Examples:
mat A(10, 10, fill::randu);
mat B(10, 10, fill::randu);
mat AA;
mat BB;
mat Q;
mat Z;
See also:
hess()
schur()
eig_pair()
generalised Schur decomposition in Wikipedia
arma.sourceforge.net/docs.html 188/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
S = schur( X )
schur( S, X )
schur( U, S, X )
Examples:
mat X(20,20, fill::randu);
mat U;
mat S;
schur(U, S, X);
See also:
hess()
qz()
eig_gen()
Schur decomposition in MathWorld
Schur decomposition in Wikipedia
arma.sourceforge.net/docs.html 189/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
X = solve( A, B )
X = solve( A, B, settings )
solve( X, A, B )
solve( X, A, B, settings )
Solve a dense system of linear equations, A*X = B, where X is unknown; similar functionality to the \ operator in
Matlab/Octave, ie. X = A \ B
A can be square sized (critically determined system), or non-square (under/over-determined system); A can be rank deficient
By default, matrix A is analysed to automatically determine whether it is a general matrix, band matrix, diagonal matrix, or
symmetric/hermitian positive definite (SPD) matrix; based on the detected matrix structure, a specialised solver is used for
faster execution; if no solution is found, an approximate solver is automatically used as a fallback; see the associated paper
for more details
If A is known to be a triangular matrix, the solution can be computed faster by explicitly indicating that A is triangular through
trimatu() or trimatl(); see examples below
fast mode: disable determining solution quality via rcond, disable iterative refinement, disable
solve_opts::fast
equilibration
solve_opts::refine apply iterative refinement to improve solution quality (matrix A must be square)
solve_opts::equilibrate equilibrate the system before solving (matrix A must be square)
solve_opts::likely_sympd indicate that matrix A is likely symmetric/hermitian positive definite
solve_opts::allow_ugly keep solutions of systems that are singular to working precision
solve_opts::no_approx do not find approximate solutions for rank deficient systems
solve_opts::no_band do not use specialised solver for band matrices or diagonal matrices
solve_opts::no_trimat do not use specialised solver for triangular matrices
solve_opts::no_sympd do not use specialised solver for symmetric/hermitian positive definite matrices
solve_opts::force_approx skip the standard solver and directly use of the approximate solver
the above settings can be combined using the + operator; for example: solve_opts::fast + solve_opts::no_approx
If a rank deficient system is detected and the solve_opts::no_approx option is not enabled, a warning is emitted and an
approximate solution is attempted;
in Armadillo 10.4 and later versions, this warning can be disabled by setting ARMA_WARN_LEVEL to 1 before including the
armadillo header:
#define ARMA_WARN_LEVEL 1
#include <armadillo>
Caveats:
using solve_opts::fast will speed up finding the solution, but for poorly conditioned systems the solution may have lower
quality
not all SPD matrices are automatically detected; to skip the analysis step and directly indicate that matrix A is likely
SPD, use solve_opts::likely_sympd
using solve_opts::force_approx is only advised if the system is known to be rank deficient; the approximate solver is
considerably slower
If no solution is found:
X = solve(A,B) resets X and throws a std::runtime_error exception
solve(X,A,B) resets X and returns a bool set to false (exception is not thrown)
Examples:
mat A(5, 5, fill::randu);
vec b(5, fill::randu);
mat B(5, 5, fill::randu);
vec x2;
bool status = solve(x2, A, b);
See also:
inv()
pinv()
rcond()
arma.sourceforge.net/docs.html 190/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
roots()
syl()
spsolve() - solve sparse system of linear equations
linear system of equations in MathWorld
system of linear equations in Wikipedia
band matrix in Wikipedia
definiteness of a matrix in Wikipedia
positive definite matrix in MathWorld
iterative refinement
arma.sourceforge.net/docs.html 191/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
vec s = svd( X )
svd( vec s, X )
Examples:
mat X(5, 5, fill::randu);
mat U;
vec s;
mat V;
svd(U,s,V,X);
See also:
svd_econ()
eig_gen()
eig_sym()
princomp()
svds()
singular value decomposition in Wikipedia
singular value decomposition in MathWorld
arma.sourceforge.net/docs.html 192/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
svd_econ( mat U, vec s, mat V, mat X )
svd_econ( mat U, vec s, mat V, mat X, mode )
svd_econ( mat U, vec s, mat V, mat X, mode, method )
If the decomposition fails, U, s, V are reset and a bool set to false is returned (exception is not thrown)
Examples:
mat X(4, 5, fill::randu);
mat U;
vec s;
mat V;
svd_econ(U, s, V, X);
See also:
svd()
eig_gen()
eig_sym()
princomp()
svds()
singular value decomposition in Wikipedia
singular value decomposition in MathWorld
arma.sourceforge.net/docs.html 193/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
X = syl( A, B, C )
syl( X, A, B, C )
If no solution is found:
syl(A,B,C) resets X and throws a std::runtime_error exception
syl(X,A,B,C) resets X and returns a bool set to false (exception is not thrown)
Examples:
mat A(5, 5, fill::randu);
mat B(5, 5, fill::randu);
mat C(5, 5, fill::randu);
mat X2;
syl(X2, A, B, C);
See also:
solve()
Sylvester equation in Wikipedia
arma.sourceforge.net/docs.html 194/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
arma.sourceforge.net/docs.html 195/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
vec eigval = eigs_sym( X, k)
vec eigval = eigs_sym( X, k, form )
vec eigval = eigs_sym( X, k, form, opts )
vec eigval = eigs_sym( X, k, sigma )
vec eigval = eigs_sym( X, k, sigma, opts )
eigs_sym( eigval, X, k)
eigs_sym( eigval, X, k, form )
eigs_sym( eigval, X, k, form, opts )
eigs_sym( eigval, X, k, sigma )
eigs_sym( eigval, X, k, sigma, opts )
Obtain a limited number of eigenvalues and eigenvectors of sparse symmetric real matrix X
The argument sigma is optional; if sigma is given, eigenvalues closest to sigma are found via shift-invert mode
NOTE: to use sigma, both ARMA_USE_ARPACK and ARMA_USE_SUPERLU must be enabled in config.hpp
The eigenvalues and corresponding eigenvectors are stored in eigval and eigvec, respectively
Caveats:
the number of obtained eigenvalues/eigenvectors may be lower than requested, depending on the given data
if the decomposition fails, try first increasing opts.subdim (Krylov subspace dimension), and, as secondary options, try
increasing opts.maxiter (maximum number of iterations), and/or opts.tol (tolerance for convergence), and/or k (number
of eigenvalues)
for an alternative to the "sm" form, use the shift-invert mode with sigma set to 0.0
Examples:
// generate sparse matrix
sp_mat A = sprandu<sp_mat>(1000, 1000, 0.1);
sp_mat B = A.t()*A;
vec eigval;
mat eigvec;
eigs_opts opts;
opts.maxiter = 10000; // increase max iterations to 10000
See also:
eigs_gen()
eig_sym()
svds()
.is_symmetric()
shift-invert mode in ARPACK
eigen decomposition in MathWorld
eigenvalues & eigenvectors in Wikipedia
arma.sourceforge.net/docs.html 196/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cx_vec eigval = eigs_gen( X, k)
cx_vec eigval = eigs_gen( X, k, form )
cx_vec eigval = eigs_gen( X, k, sigma )
cx_vec eigval = eigs_gen( X, k, form, opts )
cx_vec eigval = eigs_gen( X, k, sigma, opts )
eigs_gen( eigval, X, k)
eigs_gen( eigval, X, k, form )
eigs_gen( eigval, X, k, sigma )
eigs_gen( eigval, X, k, form, opts )
eigs_gen( eigval, X, k, sigma, opts )
Obtain a limited number of eigenvalues and eigenvectors of sparse general (non-symmetric/non-hermitian) square matrix X
The argument sigma is optional; if sigma is given, eigenvalues closest to sigma are found via shift-invert mode
NOTE: to use sigma, both ARMA_USE_ARPACK and ARMA_USE_SUPERLU must be enabled in config.hpp
The eigenvalues and corresponding eigenvectors are stored in eigval and eigvec, respectively
Caveats:
the number of obtained eigenvalues/eigenvectors may be lower than requested, depending on the given data
if the decomposition fails, try first increasing opts.subdim (Krylov subspace dimension) and, as secondary options, try
increasing opts.maxiter (maximum number of iterations), and/or opts.tol (tolerance for convergence), and/or k (number
of eigenvalues)
for an alternative to the "sm" form, use the shift-invert mode with sigma set to 0.0
Examples:
// generate sparse matrix
sp_mat A = sprandu<sp_mat>(1000, 1000, 0.1);
cx_vec eigval;
cx_mat eigvec;
eigs_opts opts;
opts.maxiter = 10000; // increase max iterations to 10000
See also:
eigs_sym()
eig_gen()
svds()
shift-invert mode in ARPACK
eigen decomposition in MathWorld
eigenvalues & eigenvectors in Wikipedia
arma.sourceforge.net/docs.html 197/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
X = spsolve( A, B )
X = spsolve( A, B, solver )
X = spsolve( A, B, solver, opts )
spsolve( X, A, B )
spsolve( X, A, B, solver )
spsolve( X, A, B, solver, opts )
Solve a sparse system of linear equations, A*X = B, where A is a sparse matrix, B is a dense matrix or vector, and X is unknown
If no solution is found:
X = spsolve(A, B) resets X and throws a std::runtime_error exception
spsolve(X, A, B) resets X and returns a bool set to false (no exception is thrown)
The solver argument is optional; solver is either "superlu" or "lapack"; by default "superlu" is used
For "superlu", ARMA_USE_SUPERLU must be enabled in config.hpp
For "lapack", sparse matrix A is converted to a dense matrix before using the LAPACK solver; this considerably increases
memory usage
Notes:
The SuperLU solver is mainly useful for very large and/or very sparse matrices
If there is sufficient amount of memory to store a dense version of matrix A, the LAPACK solver can be faster
allow_ugly is either true or false; indicates whether to keep solutions of systems singular to working precision
equilibrate is either true or false; indicates whether to equilibrate the system (scale the rows and columns of A to have
unit norm)
symmetric is either true or false; indicates whether to use SuperLU symmetric mode, which gives preference to diagonal
pivots
pivot_threshold is in the range [0.0, 1.0], used for determining whether a diagonal entry is an acceptable pivot (details
in SuperLU documentation)
Examples:
sp_mat A = sprandu<sp_mat>(1000, 1000, 0.1);
superlu_opts opts;
opts.allow_ugly = true;
opts.equilibrate = true;
See also:
solve() - solve dense system of linear equations
SuperLU home page
linear system of equations in MathWorld
system of linear equations in Wikipedia
arma.sourceforge.net/docs.html 198/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
arma.sourceforge.net/docs.html 199/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
vec s = svds( X, k )
vec s = svds( X, k, tol )
svds( vec s, X, k )
svds( vec s, X, k, tol )
Obtain a limited number of singular values and singular vectors (truncated SVD) of sparse matrix X
The singular values and vectors are calculated via sparse eigen decomposition of:
⎡ zeros(X.n_rows, X.n_rows) X ⎤
⎣ X.t() zeros(X.n_cols, X.n_cols) ⎦
The argument tol is optional; it specifies the tolerance for convergence; it is passed as (tol ÷ √2) to eigs_sym()
Caveats:
svds() is intended only for finding a few singular values from a large sparse matrix; to find all singular values, use svd()
instead
depending on the given matrix, svds() may find fewer singular values than specified
Examples:
sp_mat X = sprandu<sp_mat>(100, 200, 0.1);
mat U;
vec s;
mat V;
svds(U, s, V, X, 10);
See also:
eigs_gen()
eigs_sym()
svd()
singular value decomposition in Wikipedia
singular value decomposition in MathWorld
arma.sourceforge.net/docs.html 200/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
arma.sourceforge.net/docs.html 201/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
conv( A, B )
conv( A, B, shape )
The orientation of the result vector is the same as the orientation of A (ie. either column or row vector)
Examples:
vec A(256, fill::randu);
See also:
conv2()
fft()
cor()
interp1()
Convolution in MathWorld
Convolution in Wikipedia
FIR filter in Wikipedia
arma.sourceforge.net/docs.html 202/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
conv2( A, B )
conv2( A, B, shape )
The implementation of 2D convolution in this version is preliminary; it is not yet fully optimised
Examples:
mat A(256, 256, fill::randu);
See also:
conv()
fft2()
interp2()
Convolution in MathWorld
Convolution in Wikipedia
Kernel (image processing) in Wikipedia
arma.sourceforge.net/docs.html 203/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cx_mat Y = fft( X )
cx_mat Y = fft( X, n )
If given a matrix, the transform is done on each column vector of the matrix
If n is not specified, the transform length is the same as the length of the input vector
Caveat: the transform is fastest when the transform length is a power of 2, eg. 64, 128, 256, 512, 1024, ...
The implementation of the transform in this version is preliminary; it is not yet fully optimised
Examples:
vec X(100, fill::randu);
See also:
fft2()
conv()
real()
fast Fourier transform in MathWorld
fast Fourier transform in Wikipedia
arma.sourceforge.net/docs.html 204/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cx_mat Y = fft2( X )
cx_mat Y = fft2( X, n_rows, n_cols )
The optional arguments n_rows and n_cols specify the size of the transform; a truncated and/or zero-padded version of the
input matrix is used
Caveat: the transform is fastest when both n_rows and n_cols are a power of 2, eg. 64, 128, 256, 512, 1024, ...
The implementation of the transform in this version is preliminary; it is not yet fully optimised
Examples:
mat A(100, 100, fill::randu);
cx_mat B = fft2(A);
cx_mat C = fft2(A, 128, 128);
See also:
fft()
conv2()
real()
fast Fourier transform in MathWorld
fast Fourier transform in Wikipedia
arma.sourceforge.net/docs.html 205/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
interp1( X, Y, XI, YI )
interp1( X, Y, XI, YI, method )
interp1( X, Y, XI, YI, method, extrapolation_value )
1D data interpolation
Given a 1D function specified in vectors X and Y (where X specifies locations and Y specifies the corresponding values),
generate vector YI which contains interpolated values at locations XI
Examples:
vec x = linspace<vec>(0, 3, 20);
vec y = square(x);
vec yy;
See also:
interp2()
polyval()
linspace()
regspace()
conv()
interpolation in Wikipedia
arma.sourceforge.net/docs.html 206/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
interp2( X, Y, Z, XI, YI, ZI )
interp2( X, Y, Z, XI, YI, ZI, method )
interp2( X, Y, Z, XI, YI, ZI, method, extrapolation_value )
2D data interpolation
The vector pairs (X, Y) and (XI, YI) define 2D coordinates in a grid;
for example, X defines the horizontal coordinates and Y defines the corresponding vertical coordinates,
so that ( X(m), Y(n) ) is the 2D coordinate of element Z(n,m)
Vectors X, Y, XI, YI must contain monotonically increasing values (eg. 0.1, 0.2, 0.3, ...)
If a coordinate in the 2D grid specified by (XI, YI) is outside the domain of the 2D grid specified by (X, Y),
the corresponding value in ZI is set to extrapolation_value
Examples:
mat Z;
mat ZI;
ZI.save("output_image.pgm", pgm_binary);
See also:
interp1()
regspace()
conv2()
reshape()
bilinear interpolation in Wikipedia
arma.sourceforge.net/docs.html 207/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
P = polyfit( X, Y, N )
polyfit( P, X, Y, N )
Given a 1D function specified in vectors X and Y (where X holds independent values and Y holds the corresponding dependent
values),
model the function as a polynomial of order N and store the polynomial coefficients in column vector P
Examples:
vec x = linspace<vec>(0,4*datum::pi,100);
vec y = cos(x);
vec p = polyfit(x,y,10);
See also:
polyval()
roots()
interp1()
polynomial in Wikipedia
least squares in Wikipedia
curve fitting in Wikipedia
least squares fitting in MathWorld
arma.sourceforge.net/docs.html 208/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Y = polyval( P, X )
Given vector P of polynomial coefficients and vector X containing the independent values of a 1D function,
generate vector Y which contains the corresponding dependent values
For each x value in vector X, the corresponding y value in vector Y is generated using:
N N-1 N-2 1
y = p0x + p1x + p2x + ... + pN-1x + pN
where pi is the i-th polynomial coefficient in vector P
P must contain polynomial coefficients in descending powers (eg. generated by the polyfit() function)
Examples:
vec x1 = linspace<vec>(0,4*datum::pi,100);
vec y1 = cos(x1);
vec p1 = polyfit(x1,y1,10);
vec y2 = polyval(p1,x1);
See also:
polyfit()
roots()
interp1()
polynomial in Wikipedia
arma.sourceforge.net/docs.html 209/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
arma.sourceforge.net/docs.html 210/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
mean, median, stddev, var, range
mean( V) ⎫
mean( M) ⎪
mean( M, dim ) ⎬ mean (average value)
mean( Q) ⎪
mean( Q, dim )
⎭
median( V ) ⎫
median( M ) ⎬ median
median( M, dim ) ⎭
stddev( V) ⎫
stddev( V, norm_type ) ⎪
stddev( M) ⎬ standard deviation
stddev( M, norm_type ) ⎪
stddev( M, norm_type, dim )
⎭
var( V) ⎫
var( V, norm_type ) ⎪
var( M) ⎬ variance
var( M, norm_type ) ⎪
var( M, norm_type, dim )
⎭
range( V ) ⎫
range( M ) ⎬ range (difference between max and min)
range( M, dim ) ⎭
For vector V, return the statistic calculated using all the elements of the vector
For matrix M, find the statistic for each column (dim = 0), or each row (dim = 1)
For cube Q, find the statistics of elements along dimension dim, where dim ∈ { 0, 1, 2 }
Caveat: to obtain statistics for integer matrices/vectors (eg. umat, imat, uvec, ivec), convert to a matrix/vector with floating
point values (eg. mat, vec) using the conv_to() function
Examples:
mat A(5, 5, fill::randu);
mat B = mean(A);
mat C = var(A);
double m = mean(mean(A));
See also:
cov()
cor()
diff()
hist()
histc()
quantile()
min() & max()
running_stat - class for running statistics of scalars
running_stat_vec - class for running statistics of vectors
gmm_diag / gmm_full - model and evaluate data using Gaussian Mixture Models (GMMs)
kmeans()
arma.sourceforge.net/docs.html 211/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cov( X, Y )
cov( X, Y, norm_type )
cov( X )
cov( X, norm_type )
For two matrix arguments X and Y, if each row of X and Y is an observation and each column is a variable, the (i,j)-th entry of
cov(X,Y) is the covariance between the i-th variable in X and the j-th variable in Y
For vector arguments, the type of vector is ignored and each element in the vector is treated as an observation
The default norm_type = 0 performs normalisation using N-1 (where N is the number of observations), providing the best
unbiased estimation of the covariance matrix (if the observations are from a normal distribution). Using norm_type = 1 causes
normalisation to be done using N, which provides the second moment matrix of the observations about their mean
Examples:
mat X(4, 5, fill::randu);
mat Y(4, 5, fill::randu);
mat C = cov(X,Y);
mat D = cov(X,Y, 1);
See also:
cor()
statistics functions
running_stat_vec
Covariance in MathWorld
arma.sourceforge.net/docs.html 212/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cor( X, Y )
cor( X, Y, norm_type )
cor( X )
cor( X, norm_type )
For two matrix arguments X and Y, if each row of X and Y is an observation and each column is a variable, the (i,j)-th entry of
cor(X,Y) is the correlation coefficient between the i-th variable in X and the j-th variable in Y
For vector arguments, the type of vector is ignored and each element in the vector is treated as an observation
The default norm_type = 0 performs normalisation of the correlation matrix using N-1 (where N is the number of observations).
Using norm_type = 1 causes normalisation to be done using N
Examples:
mat X(4, 5, fill::randu);
mat Y(4, 5, fill::randu);
mat R = cor(X,Y);
mat S = cor(X,Y, 1);
See also:
cov()
conv()
statistics functions
running_stat_vec
Correlation in MathWorld
Autocorrelation in MathWorld
arma.sourceforge.net/docs.html 213/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
hist( V )
hist( V, n_bins )
hist( V, centers )
hist( X, centers )
hist( X, centers, dim )
For vector V, produce an unsigned vector of the same orientation as V (ie. either uvec or urowvec) that represents a histogram
of counts
For matrix X, produce a umat matrix containing either column histogram counts (for dim = 0, default), or row histogram counts
(for dim = 1)
The bin centers can be automatically determined from the data, with the number of bins specified via n_bins (default is 10);
the range of the bins is determined by the range of the data
The bin centers can also be explicitly specified via the centers vector; the vector must contain monotonically increasing values
(eg. 0.1, 0.2, 0.3, ...)
Examples:
vec v(1000, fill::randn); // Gaussian distribution
See also:
histc()
quantile()
statistics functions
conv_to()
arma.sourceforge.net/docs.html 214/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
histc( V, edges )
histc( X, edges )
histc( X, edges, dim )
For vector V, produce an unsigned vector of the same orientation as V (ie. either uvec or urowvec) that contains the counts of
the number of values that fall between the elements in the edges vector
For matrix X, produce a umat matrix containing either column histogram counts (for dim = 0, default), or row histogram counts
(for dim = 1)
The edges vector must contain monotonically increasing values (eg. 0.1, 0.2, 0.3, ...)
Examples:
vec v(1000, fill::randn); // Gaussian distribution
See also:
hist()
statistics functions
conv_to()
arma.sourceforge.net/docs.html 215/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
quantile( V, P )
quantile( X, P )
quantile( X, P, dim )
For a dataset stored in vector V or matrix X, calculate the quantiles corresponding to the cumulative probability values in the
given P vector
For vector V, produce a vector with the same orientation as V and the same length as P
For matrix X, produce a matrix with the quantiles for each column vector (dim = 0) or each row vector (dim = 1)
The P vector must contain values in the [0,1] interval (eg. 0.00, 0.25, 0.50, 0.75, 1.00)
Examples:
vec V(1000, fill::randn); // Gaussian distribution
See also:
hist()
median()
normcdf()
quantile in Wikipedia
arma.sourceforge.net/docs.html 216/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
mat coeff = princomp( mat X )
cx_mat coeff = princomp( cx_mat X )
princomp( mat coeff, mat score, vec latent, vec tsquared, mat X )
princomp( cx_mat coeff, cx_mat score, vec latent, cx_vec tsquared, cx_mat X )
output objects:
coeff: principal component coefficients
score: projected data
latent: eigenvalues of the covariance matrix of X
tsquared: Hotteling's statistic for each sample
Examples:
mat A(5, 4, fill::randu);
mat coeff;
mat score;
vec latent;
vec tsquared;
See also:
eig_sym()
svd()
svd_econ()
principal components analysis in Wikipedia
arma.sourceforge.net/docs.html 217/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
normpdf( X )
normpdf( X, M, S )
For each scalar x in X, compute its probability density function according to a Gaussian (normal) distribution using the
corresponding mean value m in M and the corresponding standard deviation value s in S:
1 ⎧ (x-m)2 ⎫
y = ‒‒‒‒‒‒‒ exp⎪−0.5 ‒‒‒‒‒‒ ⎪
s √(2π) ⎩ s2 ⎭
Examples:
vec X(10, fill::randu);
vec M(10, fill::randu);
vec S(10, fill::randu);
vec P1 = normpdf(X);
vec P2 = normpdf(X, M, S );
vec P3 = normpdf(1.23, M, S );
vec P4 = normpdf(X, 4.56, 7.89);
double P5 = normpdf(1.23, 4.56, 7.89);
See also:
log_normpdf()
normcdf()
randn()
gmm_diag / gmm_full - model and evaluate data using Gaussian Mixture Models (GMMs)
normal distribution in Wikipedia
arma.sourceforge.net/docs.html 218/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
log_normpdf( X )
log_normpdf( X, M, S )
For each scalar x in X, compute the logarithm version of probability density function according to a Gaussian (normal)
distribution using the corresponding mean value m in M and the corresponding standard deviation value s in S:
⎧ 1 ⎧ (x-m)2 ⎫⎫
y = log⎪‒‒‒‒‒‒‒ exp⎪−0.5 ‒‒‒‒‒‒ ⎪⎪
⎩s √(2π) ⎩ s2 ⎭⎭
⎧ (x-m)2 ⎫
= −log(s √(2π)) + ⎪−0.5 ‒‒‒‒‒‒ ⎪
⎩ s2 ⎭
Examples:
vec X(10, fill::randu);
vec M(10, fill::randu);
vec S(10, fill::randu);
vec P1 = log_normpdf(X);
vec P2 = log_normpdf(X, M, S );
vec P3 = log_normpdf(1.23, M, S );
vec P4 = log_normpdf(X, 4.56, 7.89);
double P5 = log_normpdf(1.23, 4.56, 7.89);
See also:
normpdf()
gmm_diag / gmm_full - model and evaluate data using Gaussian Mixture Models (GMMs)
normal distribution in Wikipedia
arma.sourceforge.net/docs.html 219/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
normcdf( X )
normcdf( X, M, S )
For each scalar x in X, compute its cumulative distribution function according to a Gaussian (normal) distribution using the
corresponding mean value m in M and the corresponding standard deviation value s in S
Examples:
vec X(10, fill::randu);
vec M(10, fill::randu);
vec S(10, fill::randu);
vec P1 = normcdf(X);
vec P2 = normcdf(X, M, S );
vec P3 = normcdf(1.23, M, S );
vec P4 = normcdf(X, 4.56, 7.89);
double P5 = normcdf(1.23, 4.56, 7.89);
See also:
normpdf()
quantile()
randn()
normal distribution in Wikipedia
cumulative distribution function in Wikipedia
arma.sourceforge.net/docs.html 220/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
X = mvnrnd( M, C )
X = mvnrnd( M, C, N )
mvnrnd( X, M, C )
mvnrnd( X, M, C, N )
Generate a matrix with random column vectors from a multivariate Gaussian (normal) distribution with parameters M and C:
M is the mean; must be a column vector
C is the covariance matrix; must be symmetric positive semi-definite (preferably positive definite)
Caveat: repeated generation of one vector (or a small number of vectors) using the same M and C parameters can be
inefficient;
for repeated generation consider using the generate() function in the gmm_diag and gmm_full classes
Examples:
vec M(5, fill::randu);
See also:
randn()
chi2rnd()
wishrnd()
cov()
.is_sympd()
gmm_diag / gmm_full - model and evaluate data using Gaussian Mixture Models (GMMs)
multivariate normal distribution in Wikipedia
arma.sourceforge.net/docs.html 221/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
chi2rnd( DF )
chi2rnd( DF_scalar )
chi2rnd( DF_scalar, n_elem )
chi2rnd( DF_scalar, n_rows, n_cols )
chi2rnd( DF_scalar, size(X) )
Generate a random scalar, vector or matrix with elements sampled from a chi-squared distribution with the degrees of
freedom specified by parameter DF or DF_scalar
For the chi2rnd(DF) form, the output vector/matrix has the same size and type as DF; each element in DF specifies a separate
degree of freedom
Usage:
vector_type v = chi2rnd( DF ), where the type of DF is a real vector_type
matrix_type X = chi2rnd( DF ), where the type of DF is a real matrix_type
Examples:
mat X = chi2rnd(2, 5, 6);
See also:
randg()
randn()
mvnrnd()
wishrnd()
size()
chi-squared distribution in Wikipedia
arma.sourceforge.net/docs.html 222/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
W = wishrnd( S, df )
W = wishrnd( S, df, D )
wishrnd( W, S, df )
wishrnd( W, S, df, D )
Generate a random matrix sampled from the Wishart distribution with parameters S and df:
S is a symmetric positive definite matrix (eg. a covariance matrix)
df is a scalar specifying the degrees of freedom; it can be a non-integer value
Examples:
mat X(5, 5, fill::randu);
mat S = X.t() * X;
See also:
iwishrnd()
chi2rnd()
mvnrnd()
chol()
cov()
randn()
.is_sympd()
Wishart distribution in Wikipedia
arma.sourceforge.net/docs.html 223/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
W = iwishrnd( T, df )
W = iwishrnd( T, df, Dinv )
iwishrnd( W, T, df )
iwishrnd( W, T, df, Dinv )
Generate a random matrix sampled from the inverse Wishart distribution with parameters T and df:
T is a symmetric positive definite matrix
df is a scalar specifying the degrees of freedom; it can be a non-integer value
Dinv is an optional argument; it specifies the Cholesky decomposition of the inverse of T; if Dinv is provided, T is ignored
using Dinv is more efficient if iwishrnd() needs to be used many times for the same T matrix
Examples:
mat X(5, 5, fill::randu);
mat T = X.t() * X;
See also:
wishrnd()
chol()
inv_sympd()
.is_sympd()
inverse Wishart distribution in Wikipedia
arma.sourceforge.net/docs.html 224/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
running_stat<type>
Class for running statistics (online statistics) of scalars (one dimensional process/signal)
Useful if the storage of all samples (scalars) is impractical, or if the number of samples is not known in advance
For the .var() and .stddev() functions, the default norm_type = 0 performs normalisation using N-1 (where N is the number of
samples so far), providing the best unbiased estimator; using norm_type = 1 causes normalisation to be done using N, which
provides the second moment around the mean
The return type of .count() depends on the underlying form of type: it is either float or double
Examples:
running_stat<double> stats;
See also:
running_stat_vec (running statistics of vectors)
statistics functions
gmm_diag / gmm_full - model and evaluate data using Gaussian Mixture Models (GMMs)
arma.sourceforge.net/docs.html 225/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
running_stat_vec<vec_type>
running_stat_vec<vec_type>(calc_cov)
Useful if the storage of all samples (vectors) is impractical, or if the number of samples is not known in advance
This class is similar to running_stat, with the difference that vectors are processed instead of scalars
vec_type is the vector type of the samples; for example: vec, cx_vec, rowvec, ...
The calc_cov argument is optional; by default calc_cov=false, indicating that the covariance matrix will not be calculated; to
enable the covariance matrix, use calc_cov=true during construction; for example: running_stat_vec<vec> X(true);
For the .var() and .stddev() functions, the default norm_type = 0 performs normalisation using N-1 (where N is the number of
samples so far), providing the best unbiased estimator; using norm_type = 1 causes normalisation to be done using N, which
provides the second moment around the mean
The return type of .count() depends on the underlying form of vec_type: it is either float or double
Examples:
running_stat_vec<vec> stats;
vec sample;
cout << "mean = " << endl << stats.mean() << endl;
cout << "var = " << endl << stats.var() << endl;
cout << "max = " << endl << stats.max() << endl;
//
//
running_stat_vec<rowvec> more_stats(true);
sample(1) -= sample(0);
sample(2) += sample(1);
more_stats(sample);
}
rowvec sd = more_stats.stddev();
See also:
running_stat (running statistics of scalars)
statistics functions
cov()
cor()
gmm_diag / gmm_full - model and evaluate data using Gaussian Mixture Models (GMMs)
arma.sourceforge.net/docs.html 226/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
kmeans( means, data, k, seed_mode, n_iter, print_mode )
The means parameter is the output matrix for storing the resulting centroids of the sets, with each centroid stored as a
column vector
The data parameter is the input data matrix, with each sample stored as a column vector
The k parameter indicates the number of centroids; the number of samples in the data matrix should be much larger than k
The seed_mode parameter specifies how the initial centroids are seeded; it is one of:
keep_existing use the centroids specified in the means matrix as the starting point
static_subset use a subset of the data vectors (repeatable)
random_subset use a subset of the data vectors (random)
static_spread use a maximally spread subset of data vectors (repeatable)
random_spread use a maximally spread subset of data vectors (random start)
caveat: seeding the initial centroids with static_spread and random_spread can be much more time consuming than with
static_subset and random_subset
The n_iter parameter specifies the number of clustering iterations; this is data dependent, but about 10 is typically sufficient
The print_mode parameter is either true or false, indicating whether progress is printed during clustering
If the clustering fails, the means matrix is reset and a bool set to false is returned
The clustering will run faster on multi-core machines when OpenMP is enabled in your compiler (eg. -fopenmp in GCC and
clang)
Examples:
uword d = 5; // dimensionality
uword N = 10000; // number of vectors
mat means;
if(status == false)
{
cout << "clustering failed" << endl;
}
means.print("means:");
See also:
gmm_diag / gmm_full - model and evaluate data using Gaussian Mixture Models (GMMs)
statistics functions
running_stat_vec
k-means clustering in Wikipedia
k-means clustering in MathWorld
OpenMP in Wikipedia
arma.sourceforge.net/docs.html 227/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
gmm_diag
gmm_full
Classes for multivariate data modelling and evaluation via Gaussian Mixture Models (GMMs)
The gmm_diag class is tailored for diagonal covariance matrices (ie. in each covariance matrix, all entries outside the main
diagonal are assumed to be zero)
The gmm_diag class is typically much faster to train and use than the gmm_full class, at the potential cost of some reduction
in modelling accuracy
The gmm_diag and gmm_full classes include dedicated optimisation algorithms for learning (training) the model parameters
from data:
k-means clustering, for quick initial estimates
Expectation-Maximisation (EM), for maximum-likelihood estimates
The optimisation algorithms are multi-threaded and can run much quicker on multi-core machines when OpenMP is enabled in
your compiler (eg. -fopenmp in GCC and clang)
The classes can also be used for probabilistic clustering and vector quantisation (VQ)
For an instance of gmm_diag or gmm_full named as M, the member functions and variables are:
M.log_p(V) return a scalar representing the log-likelihood of vector V (of type vec)
M.log_p(V, g) return a scalar representing the log-likelihood of vector V (of type vec), according to
Gaussian with index g
M.log_p(X) return a row vector (of type rowvec) containing log-likelihoods of each column vector in
matrix X (of type mat)
M.log_p(X, g) return a row vector (of type rowvec) containing log-likelihoods of each column vector in
matrix X (of type mat), according to Gaussian with index g
M.sum_log_p(X) return a scalar representing the sum of log-likelihoods for all column vectors in matrix
X (of type mat)
M.sum_log_p(X, g) return a scalar representing the sum of log-likelihoods for all column vectors in matrix
X (of type mat), according to Gaussian with index g
M.avg_log_p(X) return a scalar representing the average log-likelihood of all column vectors in matrix
X (of type mat)
M.avg_log_p(X, g) return a scalar representing the average log-likelihood of all column vectors in matrix
X (of type mat), according to Gaussian with index g
M.assign(V, dist_mode) return the index of the closest mean (or Gaussian) to vector V (of type vec);
parameter dist_mode is one of:
eucl_dist Euclidean distance (takes only means into account)
prob_dist probabilistic "distance", defined as the inverse likelihood (takes into
account means, covariances and hefts)
M.assign(X, dist_mode) return a row vector (of type urowvec) containing the indices of the closest means (or
Gaussians) to each column vector in matrix X (of type mat);
parameter dist_mode is either eucl_dist or prob_dist (as per the .assign() function
above)
M.raw_hist(X, dist_mode) return a row vector (of type urowvec) representing the raw histogram of counts; each
entry is the number of counts corresponding to a Gaussian; each count is the number
times the corresponding Gaussian was the closest to each column vector in matrix X;
parameter dist_mode is either eucl_dist or prob_dist (as per the .assign() function
above)
arma.sourceforge.net/docs.html 228/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
M.norm_hist(X, dist_mode) similar to the .raw_hist() function above; return a row vector (of type rowvec)
containing normalised counts; the vector sums to one;
parameter dist_mode is either eucl_dist or prob_dist (as per the .assign() function
above)
M.generate() return a column vector (of type vec) representing a random sample generated
according to the model's parameters
M.generate(N) return a matrix (of type mat) containing N column vectors, with each vector
representing a random sample generated according to the model's parameters
M.save(filename) save the model to a file and return a bool indicating either success (true) or failure
(false)
M.load(filename) load the model from a file and return a bool indicating either success (true) or failure
(false)
M.reset(n_dims, n_gaus) set the model to have dimensionality n_dims, with n_gaus number of Gaussians;
all the means are set to zero, all covariance matrix representations are equivalent to
the identity matrix, and all the hefts (weights) are set to be uniform
M.hefts read-only row vector (of type rowvec) containing the hefts (weights)
M.means read-only matrix (of type mat) containing the means (centroids), stored as column
vectors
M.dcovs read-only matrix (of type mat) containing the representation of diagonal covariance
[only in gmm_diag] matrices, with the set of diagonal covariances for each Gaussian stored as a column
vector; applicable only to the gmm_diag class
M.fcovs read-only cube containing the full covariance matrices, with each covariance matrix
[only in gmm_full] stored as a slice within the cube; applicable only to the gmm_full class
M.set_hefts(V) set the hefts (weights) of the model to be as specified in row vector V (of type
rowvec); the number of hefts must match the existing model
M.set_means(X) set the means to be as specified in matrix X (of type mat); the number of means and
their dimensionality must match the existing model
M.set_dcovs(X) set the diagonal covariances matrices to be as specified in matrix X (of type mat), with
[only in gmm_diag] the set of diagonal covariances for each Gaussian stored as a column vector; the
number of covariance matrices and their dimensionality must match the existing
model; applicable only to the gmm_diag class
M.set_fcovs(X) set the full covariances matrices to be as specified in cube X, with each covariance
[only in gmm_full] matrix stored as a slice within the cube; the number of covariance matrices and their
dimensionality must match the existing model; applicable only to the gmm_full class
M.set_params(means, covs, hefts) set all the parameters at the same time; the type and layout of the parameters is as
per the .set_hefts(), .set_means(), .set_dcovs() and .set_fcovs() functions above;
the number of Gaussians and dimensionality can be different from the existing model
data matrix (of type mat) containing training samples; each sample is stored as a column
vector
n_gaus set the number of Gaussians to n_gaus; to help convergence, it is recommended that
the given data matrix (above) contains at least 10 samples for each Gaussian
dist_mode specifies the distance used during the seeding of initial means and k-means clustering:
eucl_dist Euclidean distance
Mahalanobis distance, which uses a global diagonal covariance matrix
maha_dist estimated from the training samples; this is recommended for
probabilistic applications
seed_mode specifies how the initial means are seeded prior to running k-means and/or EM
algorithms:
keep the existing model (do not modify the means, covariances and
keep_existing
hefts)
static_subset a subset of the training samples (repeatable)
random_subset a subset of the training samples (random)
arma.sourceforge.net/docs.html 229/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
static_spread a maximally spread subset of training samples (repeatable)
random_spread a maximally spread subset of training samples (random start)
caveat: seeding the initial means with static_spread and random_spread can be much
more time consuming than with static_subset and random_subset
km_iter the number of iterations of the k-means algorithm; this is data dependent, but
typically 10 iterations are sufficient
em_iter the number of iterations of the EM algorithm; this is data dependent, but typically 5 to
10 iterations are sufficient
var_floor the variance floor (smallest allowed value) for the diagonal covariances; setting this to
a small non-zero value can help with convergence and/or better quality parameter
estimates
print_mode either true or false; enable or disable printing of progress during the k-means and EM
algorithms
Examples:
// create synthetic data with 2 Gaussians
uword d = 5; // dimensionality
uword N = 10000; // number of vectors
uword i = 0;
while(i < N)
{
if(i < N) { data.col(i) = mean0 + randn<vec>(d); ++i; }
if(i < N) { data.col(i) = mean0 + randn<vec>(d); ++i; }
if(i < N) { data.col(i) = mean1 + randn<vec>(d); ++i; }
}
gmm_diag model;
if(status == false)
{
cout << "learning failed" << endl;
}
model.means.print("means:");
model.save("my_model.gmm");
See also:
normpdf()
mvnrnd()
statistics functions
running_stat_vec
kmeans()
covariance matrix in Wikipedia
covariance matrix in MathWorld
Mahalanobis distance in Wikipedia
multivariate normal distribution in Wikipedia
mixture model in Wikipedia
k-means clustering in Wikipedia
k-means clustering in MathWorld
Expectation-Maximisation algorithm in Wikipedia
maximum likelihood in MathWorld
vector quantisation in Wikipedia
OpenMP in Wikipedia
arma.sourceforge.net/docs.html 230/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Miscellaneous
arma.sourceforge.net/docs.html 231/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
constants (pi, inf, eps, ...)
datum::eps machine epsilon; approximately 2.2204e-16; difference between 1 and the next representable value
datum::e base of the natural logarithm
datum::sqrt2 square root of 2
datum::G Newtonian constant of gravitation (in newton square meters per kilogram squared)
datum::h Planck constant (in joule seconds)
datum::h_bar Planck constant over 2 pi, aka reduced Planck constant (in joule seconds)
The constants are stored in the Datum<type> class, where type is either float or double;
for convenience, Datum<double> is typedefed as datum, and Datum<float> is typedefed as fdatum
Caveat: datum::nan is not equal to anything, even itself; to check whether a scalar x is finite, use std::isfinite(x)
The physical constants were mainly taken from NIST 2018 CODATA values, and some from WolframAlpha (as of 2009-06-23)
Examples:
cout << "speed of light = " << datum::c_0 << endl;
See also:
arma.sourceforge.net/docs.html 232/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
.is_finite()
.fill()
NaN in Wikipedia
physical constant in Wikipedia
replacement of 2π with τ in Wikipedia
The Tau Manifesto by Michael Hartl
std::numeric_limits in cplusplus.com
std::numeric_limits in cppreference.com
arma.sourceforge.net/docs.html 233/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
wall_clock
Examples:
wall_clock timer;
timer.tic();
double n = timer.toc();
See also:
elapsed real time in Wikipedia
arma.sourceforge.net/docs.html 234/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
std::ostream& x = get_cout_stream()
std::ostream& x = get_cerr_stream()
set_cout_stream( user_stream )
set_cerr_stream( user_stream )
get_cout_stream():
get a reference to the stream used for printing matrices and cubes with .print() and .raw_print()
by default this is std::cout
get_cerr_stream():
get a reference to the stream used for printing warnings and errors involving out of bounds accesses, failed
decompositions, failed loading/saving, out of memory conditions, etc
by default this is std::cerr
set_cout_stream( custom_stream ):
set the stream used for printing matrices and cubes
the stream can also be changed via the ARMA_COUT_STREAM define; see config.hpp
set_cerr_stream( custom_stream ):
change the stream for printing warnings and errors
the stream can also be changed via the ARMA_CERR_STREAM define; see config.hpp
See also:
config.hpp
.print()
std::cout
std::ostream
std::exception
tutorial on exceptions
arma.sourceforge.net/docs.html 235/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
uword, sword
uword is a typedef for an unsigned integer type; it is used for matrix indices as well as all internal counters and loops
The width can also be forcefully set to 64 bits by enabling ARMA_64BIT_WORD via editing include/armadillo_bits/config.hpp
See also:
C++ variable types
explanation of typedef
imat & umat matrix types
ivec & uvec vector types
arma.sourceforge.net/docs.html 236/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
cx_double, cx_float
Example:
cx_mat X(5, 5, fill::randu);
See also:
complex numbers in the standard C++ library
explanation of typedef
cx_mat matrix type
cx_vec vector type
arma.sourceforge.net/docs.html 237/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Examples of Matlab/Octave syntax and conceptually corresponding Armadillo syntax
A = zeros(size(A)) A.zeros()
A = ones(size(A)) A.ones()
A = zeros(k) A = zeros<mat>(k,k)
A = ones(k) A = ones<mat>(k,k)
A .* B A % B element-wise multiplication
A ./ B A / B element-wise division
A \ B solve(A,B) conceptually similar to inv(A)*B, but more efficient
A = A + 1; A++
A = A - 1; A--
A = [ 1 2; 3 4; ] A = { { 1, 2 }, element initialisation
{ 3, 4 } };
X = A(:) X = vectorise(A)
X = [ A B ] X = join_horiz(A,B)
X = [ A; B ] X = join_vert(A,B)
save ‑ascii 'A.txt' A A.save("A.txt", raw_ascii); Matlab/Octave matrices saved as ascii are readable by Armadillo
(and vice-versa)
load ‑ascii 'A.txt' A.load("A.txt", raw_ascii);
arma.sourceforge.net/docs.html 238/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
example program
#include <iostream>
#include <armadillo>
int main()
{
mat A(4, 5, fill::randu);
mat B(4, 5, fill::randu);
return 0;
}
If the above program is stored as example.cpp, under Linux and macOS it can be compiled using:
g++ example.cpp -o example -std=c++11 -O2 -larmadillo
Armadillo extensively uses template meta-programming, so it's recommended to enable optimisation when compiling programs
(eg. use the -O2 or -O3 options for GCC or clang)
See the Questions page for more info on compiling and linking
See also the example program that comes with the Armadillo archive
arma.sourceforge.net/docs.html 239/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
config.hpp
Armadillo can be configured via editing the file include/armadillo_bits/config.hpp. Specific functionality can be enabled or
disabled by uncommenting or commenting out a particular #define, listed below.
ARMA_DONT_USE_WRAPPER Disable going through the run-time Armadillo wrapper library (libarmadillo.so) when calling
LAPACK, BLAS, ARPACK, SuperLU and HDF5 functions. You will need to directly link with
BLAS, LAPACK, etc (eg. -lblas -llapack)
ARMA_USE_LAPACK Enable use of LAPACK, or a high-speed replacement for LAPACK (eg. OpenBLAS, Intel MKL,
or the Accelerate framework). Armadillo requires LAPACK for functions such as svd(), inv(),
eig_sym(), solve(), etc.
ARMA_USE_BLAS Enable use of BLAS, or a high-speed replacement for BLAS (eg. OpenBLAS, Intel MKL, or the
Accelerate framework). BLAS is used for matrix multiplication. Without BLAS, Armadillo will
use a built-in matrix multiplication routine, which might be slower for large matrices.
ARMA_USE_NEWARP Enable use of NEWARP (built-in alternative to ARPACK). This is used for the eigen
decomposition of real (non-complex) sparse matrices, ie. eigs_gen(), eigs_sym() and svds().
Requires ARMA_USE_LAPACK to be enabled. If use of both NEWARP and ARPACK is enabled,
NEWARP will be preferred.
ARMA_USE_ARPACK Enable use of ARPACK, or a high-speed replacement for ARPACK. Armadillo requires ARPACK
for the eigen decomposition of complex sparse matrices, ie. eigs_gen(), eigs_sym() and
svds(). If use of NEWARP is disabled, ARPACK will also be used for the eigen decomposition
of real sparse matrices.
ARMA_USE_SUPERLU Enable use of SuperLU, which is used by spsolve() for finding the solutions of sparse
systems, as well as eigs_sym() and eigs_gen() in shift-invert mode. You will need to link
with the superlu library, for example -lsuperlu
ARMA_USE_HDF5 Enable the ability to save and load matrices stored in the HDF5 format; the hdf5.h header
file must be available on your system and you will need to link with the hdf5 library (eg. -
lhdf5)
ARMA_DONT_USE_STD_MUTEX Disable use of std::mutex; applicable if your compiler and/or environment doesn't support
std::mutex
ARMA_DONT_OPTIMISE_BAND Disable automatically optimised handling of band matrices by solve() and chol()
ARMA_USE_OPENMP Use OpenMP for parallelisation of computationally expensive element-wise operations (such
as exp(), log(), cos(), etc). Automatically enabled when using a compiler which has OpenMP
3.1+ active (eg. the -fopenmp option for gcc and clang).
ARMA_OPENMP_THRESHOLD The minimum number of elements in a matrix to enable OpenMP based parallelisation of
computationally expensive element-wise functions; default value is 320
ARMA_OPENMP_THREADS The maximum number of threads for OpenMP based parallelisation of computationally
expensive element-wise functions; default value is 8
ARMA_BLAS_CAPITALS Use capitalised (uppercase) BLAS and LAPACK function names (eg. DGEMM vs dgemm)
ARMA_BLAS_UNDERSCORE Append an underscore to BLAS and LAPACK function names (eg. dgemm_ vs dgemm).
Enabled by default.
arma.sourceforge.net/docs.html 240/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
ARMA_BLAS_LONG Use "long" instead of "int" when calling BLAS and LAPACK functions
ARMA_BLAS_LONG_LONG Use "long long" instead of "int" when calling BLAS and LAPACK functions
ARMA_USE_FORTRAN_HIDDEN_ARGS Use so-called "hidden arguments" when calling BLAS and LAPACK functions. Enabled by
default. See Fortran argument passing conventions for more details.
ARMA_DONT_USE_FORTRAN_HIDDEN_ARGS Disable use of so-called "hidden arguments" when calling BLAS and LAPACK functions. May
be necessary when using Armadillo in conjunction with broken MKL headers (eg. if you have
#include "mkl_lapack.h" in your code).
ARMA_USE_TBB_ALLOC Use Intel TBB scalable_malloc() and scalable_free() instead of standard malloc() and free()
for managing matrix memory
ARMA_USE_MKL_ALLOC Use Intel MKL mkl_malloc() and mkl_free() instead of standard malloc() and free() for
managing matrix memory
ARMA_USE_MKL_TYPES Use Intel MKL types for complex numbers. You will need to include appropriate MKL headers
before the Armadillo header. You may also need to enable one or more of the following
options: ARMA_BLAS_LONG, ARMA_BLAS_LONG_LONG, ARMA_DONT_USE_FORTRAN_HIDDEN_ARGS
ARMA_64BIT_WORD Use 64 bit integers. Automatically enabled when using a 64-bit platform, except when using
Armadillo in the R environment (via RcppArmadillo). Useful if matrices/vectors capable of
holding more than 4 billion elements are required. This can also be enabled by adding
#define ARMA_64BIT_WORD before each instance of #include <armadillo>
ARMA_NO_DEBUG Disable all run-time checks, such as bounds checking. This will result in faster code, but
you first need to make sure that your code runs correctly! We strongly recommend to have
the run-time checks enabled during development, as this greatly aids in finding mistakes in
your code, and hence speeds up development. We recommend that run-time checks be
disabled only for the shipped version of your program (ie. final release build).
ARMA_EXTRA_DEBUG Print out the trace of internal functions used for evaluating expressions. Not recommended
for normal use. This is mainly useful for debugging the library.
ARMA_MAT_PREALLOC The number of pre-allocated elements used by matrices and vectors. Must be always
enabled and set to an integer that is at least 1. By default set to 16. If you mainly use lots
of very small vectors (eg. ≤ 4 elements), change the number to the size of your vectors.
ARMA_COUT_STREAM The default stream used for printing matrices and cubes by .print(). Must be always
enabled. By default defined to std::cout
ARMA_CERR_STREAM The default stream used for printing warnings and errors. Must be always enabled. By
default defined to std::cerr
See also:
element access
element initialisation
uword/sword
output streams
arma.sourceforge.net/docs.html 241/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
History of API Additions, Changes and Deprecations
Each release of Armadillo has its public API (functions, classes, constants) described in the accompanying API
documentation specific to that release.
Each release of Armadillo has its full version specified as A.B.C, where A is a major version number, B is a minor version
number, and C is a patch level (indicating bug fixes).
Within a major version (eg. 7), each minor version has a public API that strongly strives to be backwards compatible (at
the source level) with the public API of preceding minor versions. For example, user code written for version 7.100
should work with version 7.200, 7.300, 7.400, etc. However, as later minor versions may have more features (API
extensions) than preceding minor versions, user code specifically written for version 7.400 may not work with 7.300.
An increase in the patch level, while the major and minor versions are retained, indicates modifications to the code
and/or documentation which aim to fix bugs without altering the public API.
We don't like changes to existing public API and strongly prefer not to break any user software. However, to allow
evolution, we reserve the right to alter the public API in future major versions of Armadillo while remaining backwards
compatible in as many cases as possible (eg. major version 8 may have slightly different public API than major version 7).
Caveat: any function, class, constant or other code not explicitly described in the public API documentation is
considered as part of the underlying internal implementation details, and may be removed or changed without notice.
(In other words, don't use internal functionality).
Version 11.2:
faster handling of sparse submatrix column views by norm(), accu(), nonzeros()
extended randu() and randn() to allow specification of distribution parameters
Version 11.1:
added inv_opts::no_ugly option to inv() and inv_sympd() to disallow inverses of poorly conditioned matrices
more efficient handling of rank-deficient matrices via inv_opts::allow_approx option in inv() and inv_sympd()
better detection of rank deficient matrices by solve()
faster handling of symmetric and diagonal matrices by cond()
Version 11.0:
added variants of inv() and inv_sympd() that provide rcond (reciprocal condition number)
expanded inv() and inv_sympd() with options inv_opts::tiny and inv_opts::allow_approx
stricter handling of singular matrices by inv() and inv_sympd()
stricter handling of non-sympd matrices by inv_sympd()
stricter handling of non-finite matrices by pinv()
more robust handling of rank deficient matrices by solve()
faster handling of diagonal matrices by rcond()
changed eigs_sym() and eigs_gen() to use higher quality RNG
quantile() and median() will now throw an exception if given matrices/vectors have NaN elements
Version 10.8:
faster handling of symmetric matrices by pinv() and rank()
faster handling of diagonal matrices by inv_sympd(), pinv(), rank()
expanded norm() to handle integer vectors and matrices
added datum::tau to replace 2π
Version 10.7:
faster handling of submatrix views accessed by X.cols(first_col,last_col)
faster handling of element-wise min() and max() in compound expressions
expanded solve() with solve_opts::force_approx option to force use of the approximate solver
Version 10.6:
expanded chol() to optionally use pivoted decomposition
expanded vector, matrix and cube constructors to allow element initialisation via fill::value(scalar), eg. mat
X(4,5,fill::value(123))
faster loading of CSV files when using OpenMP
added csv_opts::semicolon option to allow saving/loading of CSV files with semicolon (;) instead of comma (,) as
the separator
Version 10.5:
added .clamp() member function
expanded the standalone clamp() function to handle complex values
more efficient use of OpenMP
vector, matrix and cube constructors now initialise elements to zero by default;
element initialisation can be disabled via the fill::none specifier, eg. mat X(4,5,fill::none)
Version 10.4:
faster handling of triangular matrices by log_det()
added log_det_sympd() for log determinant of symmetric positive matrices
added ARMA_WARN_LEVEL configuration option, to control the degree of emitted warning messages
reduced the default degree of warning messages, so that failed decompositions, failed saving/loading, etc, no
longer emit warnings
arma.sourceforge.net/docs.html 242/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Version 10.3:
faster handling of symmetric positive definite matrices by pinv()
expanded .save() / .load() for dense matrices to handle coord_ascii format
for out of bounds access, element accessors now throw the more nuanced std::out_of_range exception, instead of
only std::logic_error
improved quality of random numbers
Version 10.2:
faster handling of subcubes
added tgamma()
added .brief_print() for abridged printing of matrices & cubes
expanded sparse matrix forms of trimatu() and trimatl() to allow specifying the diagonal delimiter
expanded eigs_sym() and eigs_gen() with optional shift-invert mode
Version 10.1:
C++11 is now the minimum required C++ standard
faster handling of compound expressions by trimatu() and trimatl()
faster sparse matrix addition, subtraction and element-wise multiplication
expanded sparse submatrix views to handle the non-contiguous form of X.cols(vector_of_column_indices)
expanded eigs_sym() and eigs_gen() with optional fine-grained parameters
Version 9.900:
faster solve() for under/over-determined systems
faster eig_gen() and eig_pair() for large matrices
faster handling of matrix multiplication expressions by diagvec() and diagmat()
faster handling of relational expressions by accu()
faster handling of sympd matrices by expmat(), logmat(), sqrtmat()
faster access to columns in sparse submatrix views
added quantile()
added powmat()
added trimatu_ind() and trimatl_ind()
added log_normpdf()
added .is_zero()
added ARMA_DONT_USE_CXX11_MUTEX configuration option to disable use of std::mutex
expanded eig_gen() and eig_pair() to optionally provide left and right eigenvectors
expanded qr() to optionally use pivoted decomposition
expanded .save() and .load() to handle CSV files with headers via csv_name(filename,header) specification
more consistent detection of sparse vector expressions
updated physical constants to NIST 2018 CODATA values
workaround for save/load issues with HDF5 v1.12
Version 9.800:
faster solve() in default operation; iterative refinement is no longer applied by default; use solve_opts::refine to
explicitly enable refinement
faster expmat()
faster handling of triangular matrices by rcond()
added .front() and .back()
added .is_trimatu() and .is_trimatl()
added .is_diagmat()
Version 9.700:
faster handling of cubes by vectorise()
faster handling of sparse matrices by nonzeros()
faster row-wise index_min() and index_max()
expanded join_rows() and join_cols() to handle joining up to 4 matrices
expanded .save() and .load() to allow storing sparse matrices in CSV format
added randperm() to generate a vector with random permutation of a sequence of integers
Version 9.600:
faster handling of sparse submatrices
faster handling of sparse diagonal views
faster handling of sparse matrices by symmatu() and symmatl()
faster handling of sparse matrices by join_cols()
expanded clamp() to handle sparse matrices
added .clean() to replace elements below a threshold with zeros
Version 9.500:
expanded solve() with solve_opts::likely_sympd to indicate that the given matrix is likely positive definite
more robust automatic detection of positive definite matrices by solve() and inv()
faster handling of sparse submatrices
expanded eigs_sym() to print a warning if the given matrix is not symmetric
extended LAPACK function prototypes to follow Fortran passing conventions for so-called "hidden arguments", in
order to address GCC Bug 90329;
to use previous LAPACK function prototypes without the "hidden arguments", #define
ARMA_DONT_USE_FORTRAN_HIDDEN_ARGS before #include <armadillo>
Version 9.400:
faster cov() and cor()
added .as_col() and .as_row()
expanded .shed_rows() / .shed_cols() / .shed_slices() to remove rows/columns/slices specified in a vector
expanded vectorise() to handle sparse matrices
arma.sourceforge.net/docs.html 243/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
expanded element-wise versions of max() and min() to handle sparse matrices
optimised handling of sparse matrix expressions: sparse % (sparse +- scalar) and sparse / (sparse +- scalar)
expanded eig_sym(), chol(), expmat_sym(), logmat_sympd(), sqrtmat_sympd(), inv_sympd() to print a warning if
the given matrix is not symmetric
more consistent detection of vector expressions
Version 9.300:
faster handling of compound complex matrix expressions by trace()
more efficient handling of element access for inplace modifications in sparse matrices
added .is_sympd() to check whether a matrix is symmetric/hermitian positive definite
added interp2() for 2D data interpolation
added expm1() and log1p()
expanded .is_sorted() with options "strictascend" and "strictdescend"
expanded eig_gen() to optionally perform balancing prior to decomposition
Version 9.200:
faster handling of symmetric positive definite matrices by rcond()
faster transpose of matrices with size ≥ 512x512
faster handling of compound sparse matrix expressions by accu(), diagmat(), trace()
faster handling of sparse matrices by join_rows()
added sinc()
expanded sign() to handle scalar arguments
expanded operators (*, %, +, −) to handle sparse matrices with differing element types (eg. multiplication of
complex matrix by real matrix)
expanded conv_to() to allow conversion between sparse matrices with differing element types
expanded solve() to optionally allow keeping solutions of systems singular to working precision
Version 9.100:
faster handling of symmetric/hermitian positive definite matrices by solve()
faster handling of inv_sympd() in compound expressions
added .is_symmetric()
added .is_hermitian()
expanded spsolve() to optionally allow keeping solutions of systems singular to working precision
new configuration options ARMA_OPTIMISE_SOLVE_BAND and ARMA_OPTIMISE_SOLVE_SYMPD
smarter use of the element cache in sparse matrices
Version 8.600:
added hess() for Hessenberg decomposition
added .row(), .rows(), .col(), .cols() to subcube views
expanded .shed_rows() and .shed_cols() to handle cubes
expanded .insert_rows() and .insert_cols() to handle cubes
expanded subcube views to allow non-contiguous access to slices
improved tuning of sparse matrix element access operators
faster handling of tridiagonal matrices by solve()
faster multiplication of matrices with differing element types when using OpenMP
Version 8.500:
faster handling of sparse matrices by kron() and repmat()
faster transpose of sparse matrices
faster element access in sparse matrices
faster row iterators for sparse matrices
faster handling of compound expressions by trace()
more efficient handling of aliasing in submatrix views
expanded normalise() to handle sparse matrices
expanded .transform() and .for_each() to handle sparse matrices
added reverse() for reversing order of elements
added repelem() for replicating elements
added roots() for finding the roots of a polynomial
Version 8.400:
faster handling of sparse matrices by repmat()
faster loading of CSV files
expanded kron() to handle sparse matrices
expanded index_min() and index_max() to handle cubes
expanded randi(), randu(), randn(), randg() to output single scalars
added submatrix & subcube iterators
added normcdf()
added mvnrnd()
added chi2rnd()
added wishrnd() and iwishrnd()
Version 8.300:
faster handling of band matrices by solve()
faster handling of band matrices by chol()
faster randg() when using OpenMP
added normpdf()
expanded .save() to allow appending new datasets to existing HDF5 files
Version 8.200:
added intersect() for finding common elements in two vectors/matrices
expanded affmul() to handle non-square matrices
arma.sourceforge.net/docs.html 244/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Version 8.100:
faster incremental construction of sparse matrices via element access operators
faster diagonal views in sparse matrices
expanded SpMat to save/load sparse matrices in coord format
expanded .save()/.load() to allow specification of datasets within HDF5 files
added affmul() to simplify application of affine transformations
warnings and errors are now printed by default to the std::cerr stream
added set_cerr_stream() and get_cerr_stream() to replace set_stream_err1(), set_stream_err2(),
get_stream_err1(), get_stream_err2()
new configuration options ARMA_COUT_STREAM and ARMA_CERR_STREAM
Version 7.960:
faster randn() when using OpenMP
faster gmm_diag class, for Gaussian mixture models with diagonal covariance matrices
added .sum_log_p() to the gmm_diag class
added gmm_full class, for Gaussian mixture models with full covariance matrices
expanded .each_slice() to optionally use OpenMP for multi-threaded execution
Version 7.950:
expanded accu() and sum() to use OpenMP for processing expressions with computationally expensive element-wise
functions
expanded trimatu() and trimatl() to allow specification of the diagonal which delineates the boundary of the
triangular part
Version 7.900:
expanded clamp() to handle cubes
computationally expensive element-wise functions (such as exp(), log(), cos(), etc) can now be automatically sped
up via OpenMP; this requires a C++11/C++14 compiler with OpenMP 3.1+ support
for GCC and clang compilers use the following options to enable both C++11 and OpenMP: -std=c++11 -fopenmp
Caveat: when using GCC, use of -march=native in conjunction with -fopenmp may lead to speed regressions on
recent processors
Version 7.800:
changed license to the permissive Apache License 2.0; see the Questions page for more info
Version 7.700:
added polyfit() and polyval()
added second form of log_det() to directly return the result as a complex number
added range() to statistics functions
expanded trimatu()/trimatl() and symmatu()/symmatl() to handle sparse matrices
Version 7.600:
more accurate eigs_sym() and eigs_gen()
expanded floor(), ceil(), round(), trunc(), sign() to handle sparse matrices
added arg(), atan2(), hypot()
Version 7.500:
expanded qz() to optionally specify ordering of the Schur form
expanded .each_slice() to support matrix multiplication
Version 7.400:
added expmat_sym(), logmat_sympd(), sqrtmat_sympd()
added .replace()
Version 7.300:
added index_min() and index_max() standalone functions
expanded .subvec() to accept size() arguments
more robust handling of non-square matrices by lu()
Version 7.200:
added .index_min() and .index_max() member functions
expanded ind2sub() to handle vectors of indices
expanded sub2ind() to handle matrix of subscripts
expanded expmat(), logmat() and sqrtmat() to optionally return a bool indicating success
faster handling of compound expressions by vectorise()
Version 7.100:
added erf(), erfc(), lgamma()
added .head_slices() and .tail_slices() to subcube views
spsolve() now requires SuperLU 5.2
eigs_sym(), eigs_gen() and svds() now use a built-in reimplementation of ARPACK for real (non-complex) matrices;
contributed by Yixuan Qiu
Version 6.700:
added trapz() for numerical integration
added logmat() for calculating the matrix logarithm
added regspace() for generating vectors with regularly spaced elements
added logspace() for generating vectors with logarithmically spaced elements
added approx_equal() for determining approximate equality
Version 6.600:
expanded sum(), mean(), min(), max() to handle cubes
arma.sourceforge.net/docs.html 245/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
expanded Cube class to handle arbitrarily sized empty cubes (eg. 0x5x2)
added shift() for circular shifts of elements
added sqrtmat() for finding the square root of a matrix
Version 6.500:
added conv2() for 2D convolution
added stand-alone kmeans() function for clustering data
added trunc()
extended conv() to optionally provide central convolution
faster handling of multiply-and-accumulate by accu() when using Intel MKL, ATLAS or OpenBLAS
Version 6.400:
expanded each_col(), each_row() and each_slice() to handle C++11 lambda functions
added ind2sub() and sub2ind()
Version 6.300:
expanded solve() to find approximate solutions for rank-deficient systems
faster handling of non-contiguous submatrix views in compound expressions
added .for_each() to Mat, Row, Col, Cube and field classes
added rcond() for estimating the reciprocal condition number
Version 6.200:
expanded diagmat() to handle non-square matrices and arbitrary diagonals
expanded trace() to handle non-square matrices
Version 6.100:
faster norm() and normalise() when using Intel MKL, ATLAS or OpenBLAS
added Schur decomposition: schur()
stricter handling of matrix objects by hist() and histc()
advanced constructors for using auxiliary memory by Mat, Col, Row and Cube now have the default of strict = false
Cube class now delays allocation of .slice() related structures until needed
expanded join_slices() to handle joining cubes with matrices
Version 5.600:
added .each_slice() for repeated matrix operations on each slice of a cube
expanded .each_col() and .each_row() to handle out-of-place operations
Version 5.500:
expanded object constructors and generators to handle size() based specification of dimensions
Version 5.400:
added find_unique() for finding indices of unique values
added diff() for calculating differences between consecutive elements
added cumprod() for calculating cumulative product
added null() for finding the orthonormal basis of null space
expanded interp1() to handle repeated locations
expanded unique() to handle complex numbers
faster flipud()
faster row-wise cumsum()
Version 5.300:
added generalised Schur decomposition: qz()
added .has_inf() and .has_nan()
expanded interp1() to handle out-of-domain locations
expanded sparse matrix class with .set_imag() and .set_real()
expanded imag(), real() and conj() to handle sparse matrices
expanded diagmat(), reshape() and resize() to handle sparse matrices
faster sparse sum()
faster row-wise sum(), mean(), min(), max()
updated physical constants to NIST 2014 CODATA values
Version 5.200:
added orth() for finding the orthonormal basis of the range space of a matrix
expanded element initialisation to handle nested initialiser lists (C++11)
Version 5.100:
added interp1() for 1D interpolation
added .is_sorted() for checking whether a vector or matrix has sorted elements
updated physical constants to NIST 2010 CODATA values
Version 5.000:
added spsolve() for solving sparse systems of linear equations
added svds() for singular value decomposition of sparse matrices
added nonzeros() for extracting non-zero values from matrices
added handling of diagonal views by sparse matrices
expanded repmat() to handle sparse matrices
expanded join_rows() and join_cols() to handle sparse matrices
sort_index() and stable_sort_index() have been placed in the delayed operations framework for increased
efficiency
use of 64 bit integers is automatically enabled when using a C++11 compiler
Version 4.650:
arma.sourceforge.net/docs.html 246/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
added randg() for generating random values from gamma distributions (C++11 only)
added .head_rows() and .tail_rows() to submatrix views
added .head_cols() and .tail_cols() to submatrix views
expanded eigs_sym() to optionally calculate eigenvalues with smallest/largest algebraic values
Version 4.600:
added .head() and .tail() to submatrix views
faster matrix transposes within compound expressions
faster in-place matrix multiplication
faster accu() and norm() when compiling with -O3 -ffast-math -march=native (gcc and clang)
Version 4.550:
added matrix exponential function: expmat()
faster .log_p() and .avg_log_p() functions in the gmm_diag class when compiling with OpenMP enabled
faster handling of in-place addition/subtraction of expressions with an outer product
Version 4.500:
faster handling of complex vectors by norm()
expanded chol() to optionally specify output matrix as upper or lower triangular
better handling of non-finite values when saving matrices as text files
Version 4.450:
faster handling of matrix transposes within compound expressions
expanded symmatu()/symmatl() to optionally disable taking the complex conjugate of elements
expanded sort_index() to handle complex vectors
expanded the gmm_diag class with functions to generate random samples
Version 4.400:
faster handling of subvectors by dot()
faster handling of aliasing by submatrix views
added clamp() for clamping values to be between lower and upper limits
added gmm_diag class for statistical modelling of data using Gaussian Mixture Models
expanded batch insertion constructors for sparse matrices to add values at repeated locations
Version 4.320:
expanded eigs_sym() and eigs_gen() to use an optional tolerance parameter
expanded eig_sym() to automatically fall back to standard decomposition method if divide-and-conquer fails
cmake-based installer enables use of C++11 random number generator when using gcc 4.8.3+ in C++11 mode
Version 4.300:
added find_finite() and find_nonfinite()
expressions X=inv(A)*B*C and X=A.i()*B*C are automatically converted to X=solve(A,B*C)
Version 4.200:
faster transpose of sparse matrices
more efficient handling of aliasing during matrix multiplication
faster inverse of matrices marked as diagonal
Version 4.100:
added normalise() for normalising vectors to unit p-norm
extended the field class to handle 3D layout
extended eigs_sym() and eigs_gen() to obtain eigenvalues of various forms (eg. largest or smallest magnitude)
automatic SIMD vectorisation of elementary expressions (eg. matrix addition) when using Clang 3.4+ with -O3
optimisation
faster handling of sparse submatrix views
Version 4.000:
added eigen decompositions of sparse matrices: eigs_sym() and eigs_gen()
added eigen decomposition for pair of matrices: eig_pair()
added simpler forms of eig_gen()
added condition number of matrices: cond()
expanded find() to handle cubes
expanded subcube views to access elements specified in a vector
template argument for running_stat_vec expanded to accept vector types
more robust fast inverse of 4x4 matrices
faster divide-and-conquer decompositions are now used by default for eig_sym(), pinv(), princomp(), rank(), svd(),
svd_econ()
the form inv(sympd(X)) no longer assumes that X is positive definite; use inv_sympd() instead
Version 3.930:
added size() based specifications of submatrix view sizes
added element-wise variants of min() and max()
added divide-and-conquer variant of svd_econ()
added divide-and-conquer variant of pinv()
added randi() for generating matrices with random integer values
added inplace_trans() for memory efficient in-place transposes
added more intuitive specification of sort direction in sort() and sort_index()
added more intuitive specification of method in det(), .i(), inv() and solve()
more precise timer for the wall_clock class when using C++11
Version 3.920:
faster .zeros()
arma.sourceforge.net/docs.html 247/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
faster round(), exp2() and log2() when using C++11
added signum function: sign()
added move constructors when using C++11
added 2D fast Fourier transform: fft2()
added .tube() for easier extraction of vectors and subcubes from cubes
added specification of a fill type during construction of Mat, Col, Row and Cube classes, eg. mat X(4, 5, fill::zeros)
Version 3.910:
faster multiplication of a matrix with a transpose of itself, ie. X*X.t() and X.t()*X
added vectorise() for reshaping matrices into vectors
added all() and any() for indicating presence of elements satisfying a relational condition
Version 3.900:
added automatic SSE2 vectorisation of elementary expressions (eg. matrix addition) when using GCC 4.7+ with -O3
optimisation
faster median()
faster handling of compound expressions with transposes of submatrix rows
faster handling of compound expressions with transposes of complex vectors
added support for saving & loading of cubes in HDF5 format
Version 3.820:
faster as_scalar() for compound expressions
faster transpose of small vectors
faster matrix-vector product for small vectors
faster multiplication of small fixed size matrices
Version 3.810:
added fast Fourier transform: fft()
added handling of .imbue() and .transform() by submatrices and subcubes
added batch insertion constructors for sparse matrices
Version 3.800:
added .imbue() for filling a matrix/cube with values provided by a functor or lambda expression
added .swap() for swapping contents with another matrix
added .transform() for transforming a matrix/cube using a functor or lambda expression
added round() for rounding matrix elements towards nearest integer
faster find()
changed license to the Mozilla Public License 2.0
Version 3.6:
faster handling of compound expressions with submatrices and subcubes
faster trace()
added support for loading matrices as text files with NaN and Inf elements
added stable_sort_index(), which preserves the relative order of elements with equivalent values
added handling of sparse matrices by mean(), var(), norm(), abs(), square(), sqrt()
added saving and loading of sparse matrices in arma_binary format
Version 3.4:
added economical QR decomposition: qr_econ()
added .each_col() & .each_row() for vector operations repeated on each column or row of a matrix
added preliminary support for sparse matrices
added ability to save and load matrices in HDF5 format
faster singular value decomposition via optional use of divide-and-conquer algorithm
faster .randn()
faster dot() and cdot() for complex numbers
Version 3.2:
added unique(), for finding unique elements of a matrix
added .eval(), for forcing the evaluation of delayed expressions
faster eigen decomposition via optional use of divide-and-conquer algorithm
faster transpose of vectors and compound expressions
faster handling of diagonal views
faster handling of tiny fixed size vectors (≤ 4 elements)
Version 3.0:
added shorthand for inverse: .i()
added datum class
added hist() and histc()
added non-contiguous submatrix views
faster handling of submatrix views with a single row or column
faster element access in fixed size matrices
faster repmat()
expressions X=inv(A)*B and X=A.i()*B are automatically converted to X=solve(A,B)
better detection of vector expressions by sum(), cumsum(), prod(), min(), max(), mean(), median(), stddev(), var()
faster generation of random numbers (eg. randu() and randn()), via an algorithm that produces slightly different
numbers than in 2.x
support for tying writable auxiliary (external) memory to fixed size matrices has been removed; instead, you can
use standard matrices with writable auxiliary memory, or initialise fixed size matrices by copying the memory;
using auxiliary memory with standard matrices is unaffected
.print_trans() and .raw_print_trans() have been removed; instead, you can chain .t() and .print() to achieve a
similar result: X.t().print()
arma.sourceforge.net/docs.html 248/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
Version 2.4:
added shorter forms of transposes: .t() and .st()
added .resize() and resize()
added optional use of 64 bit indices (allowing matrices to have more than 4 billion elements), enabled via
ARMA_64BIT_WORD in include/armadillo_bits/config.hpp
added experimental support for C++11 initialiser lists, enabled via ARMA_USE_CXX11 in
include/armadillo_bits/config.hpp
refactored code to eliminate warnings when using the Clang C++ compiler
umat, uvec, .min() and .max() have been changed to use the uword type instead of the u32 type; by default the
uword and u32 types are equivalent (ie. unsigned integer type with a minimum width 32 bits); however, when the
use of 64 bit indices is enabled via ARMA_64BIT_WORD in include/armadillo_bits/config.hpp, the uword type then
has a minimum width of 64 bits
Version 2.2:
added svd_econ()
added circ_toeplitz()
added .is_colvec() and .is_rowvec()
Version 2.0:
det(), inv() and solve() can be forced to use more precise algorithms for tiny matrices (≤ 4x4)
added syl(), for solving Sylvester's equation
added strans(), for transposing a complex matrix without taking the complex conjugate
added symmatu() and symmatl()
added submatrices of submatrices
faster inverse of symmetric positive definite matrices
faster element access for fixed size matrices
faster multiplication of tiny matrices (eg. 4x4)
faster compound expressions containing submatrices
added handling of arbitrarily sized empty matrices (eg. 5x0)
added .count() member function in running_stat and running_stat_vec
added loading & saving of matrices as CSV text files
trans() now takes the complex conjugate when transposing a complex matrix
forms of chol(), eig_sym(), eig_gen(), inv(), lu(), pinv(), princomp(), qr(), solve(), svd(), syl() that do not return a
bool indicating success now throw std::runtime_error exceptions when failures are detected
princomp_cov() has been removed; eig_sym() in conjunction with cov() can be used instead
.is_vec() now outputs true for empty vectors (eg. 0x1)
set_log_stream() & get_log_stream() have been replaced by set_stream_err1() & get_stream_err1()
Version 1.2:
added .min() & .max() member functions of Mat and Cube
added floor() and ceil()
added representation of “not a number”: math::nan()
added representation of infinity: math::inf()
.in_range() expanded to use span() arguments
fixed size matrices and vectors can use auxiliary (external) memory
submatrices and subfields can be accessed via X( span(a,b), span(c,d) )
subcubes can be accessed via X( span(a,b), span(c,d), span(e,f) )
the two argument version of span can be replaced by span::all or span(), to indicate an entire range
for cubes, the two argument version of span can be replaced by a single argument version, span(a), to indicate a
single column, row or slice
arbitrary "flat" subcubes can be interpreted as matrices; for example:
cube Q = randu<cube>(5,3,4);
mat A = Q( span(1), span(1,2), span::all );
// A has a size of 2x4
vec v = ones<vec>(4);
Q( span(1), span(1), span::all ) = v;
rand() has been replaced by randu(); this has been done to avoid confusion with std::rand(), which generates
random numbers in a different interval
In versions earlier than 0.9.0, some multiplication operations directly converted result matrices with a size of 1x1
into scalars. This is no longer the case. If you know the result of an expression will be a 1x1 matrix and wish to
treat it as a pure scalar, use the as_scalar() wrapping function
Almost all functions have been placed in the delayed operations framework (for speed purposes). This may affect
code which assumed that the output of some functions was a pure matrix. The solution is easy, as explained below.
In general, Armadillo queues operations before executing them. As such, the direct output of an operation or
function cannot be assumed to be a directly accessible matrix. The queued operations are executed when the
output needs to be stored in a matrix, eg. mat B = trans(A) or mat B(trans(A)). If you need to force the execution
of the delayed operations, place the operation or function inside the corresponding Mat constructor. For example,
arma.sourceforge.net/docs.html 249/250
6/18/22, 10:22 AM Armadillo: C++ library for linear algebra & scientific computing - API Documentation
if your code assumed that the output of some functions was a pure matrix, eg. chol(m).diag(), change the code to
mat(chol(m)).diag(). Similarly, if you need to pass the result of an operation such as A+B to one of your own
functions, use my_function( mat(A+B) ).
arma.sourceforge.net/docs.html 250/250