Armadillo_ C++ Linear Algebra Library
Armadillo_ C++ Linear Algebra Library
Armadillo
C++ linear algebra library
If you discover any bugs or regressions, please report them Conrad Sanderson. Armadillo: An Open Sourc
Library for Fast Prototyping and Computation
History of API additions Experiments. Technical Report, NICTA, 2010.
Overview
http://arma.sourceforge.net/docs.html 1/202
4/25/2016 Armadillo: C++ linear algebra library
.each_col / .each_row repeated operations on each column or row of matrix
.each_slice repeated operations on each slice of cube
iterators (matrices) STL‐style iterators and associated member functions for matrices and vectors
iterators (cubes) STL‐style iterators and associated member functions for cubes
STL container functions STL‐style 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
Functions of Vectors/Matrices/Cubes
http://arma.sourceforge.net/docs.html 2/202
4/25/2016 Armadillo: C++ linear algebra library
find_finite find indices of finite elements
find_nonfinite find indices of non‐finite elements
find_unique find indices of unique elements
fliplr / flipud reverse order of columns or rows
imag / real extract imaginary/real part
ind2sub convert linear index to subscripts
inplace_trans in‐place transpose
is_finite check whether all elements are finite
join_rows / join_cols concatenation of matrices
join_slices concatenation of cubes
kron Kronecker tensor product
logmat matrix logarithm
min / max return extremum values
nonzeros return non‐zero values
norm various norms of vectors and matrices
normalise normalise vectors to unit p‐norm
prod product of elements
rank rank of matrix
rcond reciprocal of condition number
repmat replicate matrix in block‐like fashion
reshape change size while keeping elements
resize change size while keeping elements and preserving layout
shift shift elements
shuffle randomly shuffle elements
size obtain dimensions of given object
sort sort elements
sort_index vector describing sorted order of elements
sqrtmat square root of matrix
sum sum of elements
sub2ind convert subscripts to linear index
symmatu / symmatl generate symmetric matrix from given matrix
trace sum of diagonal elements
trans transpose of matrix
trapz trapezoidal numerical integration
trimatu / trimatl generate triangular matrix from given matrix
unique return unique elements
vectorise convert matrix to 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 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
http://arma.sourceforge.net/docs.html 3/202
4/25/2016 Armadillo: C++ linear algebra library
fft2 / ifft2 2D fast Fourier transform and its inverse
interp1 1D interpolation
Miscellaneous
http://arma.sourceforge.net/docs.html 4/202
4/25/2016 Armadillo: C++ linear algebra library
http://arma.sourceforge.net/docs.html 5/202
4/25/2016 Armadillo: C++ linear algebra library
Mat<type>
mat
cx_mat
In this documentation the mat type is used for convenience; it is possible to use other types instead, eg. fmat
Functions which use LAPACK or ATLAS (generally matrix decompositions) are only valid for the following types:
cx_fmat
Constructors:
mat()
mat(n_rows, n_cols)
mat(n_rows, n_cols, fill_type)
mat(size(X))
mat(size(X), fill_type)
mat(mat)
mat(sp_mat)
mat(vec)
mat(rowvec)
mat(initializer_list)
mat(string)
mat(std::vector) (treated as a column vector)
cx_mat(mat,mat) (for constructing a complex matrix out of two real matrices)
When specifying the size with n_rows and n_cols, by default the memory is uninitialised; memory can be initialised
fill_type, which is one of: fill::zeros, fill::ones, fill::eye, fill::randu, fill::randn, fill::none, with the following me
fill::zeros = set all elements to 0
fill::ones = set all elements to 1
fill::eye = set the elements along the main diagonal to 1 and off‐diagonal elements to 0
fill::randu = set each element to a random value from a uniform distribution in the [0,1] interval
fill::randn = set each element to a random value from a normal/Gaussian distribution with zero mean and u
fill::none = do not modify the elements
The string format for the constructor is elements separated by spaces, and rows denoted by semicolons. For examp
matrix can be created using "1 0; 0 1".
Caveat: string based initialisation is slower than directly setting the elements or using element initialisation
Advanced constructors:
Create a matrix using data from writable auxiliary (external) memory, where ptr_aux_mem is a pointer
default the matrix allocates its own memory and copies data from the auxiliary memory (for safety). Ho
copy_aux_mem is set to false, the matrix will instead directly use the auxiliary memory (ie. no copying)
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 direct
memory)
when strict is set to false, the matrix will use the auxiliary memory until a size change
when strict is set to true, the matrix will be bound to the auxiliary memory for its lifetime; the nu
the matrix can't be changed
the default setting of strict in versions 6.000+ is false
the default setting of strict in versions 5.600 and earlier is true
Create a matrix by copying data from read‐only auxiliary memory, where ptr_aux_mem is a pointer to t
mat::fixed<n_rows, n_cols>
Create a fixed size matrix, with the size specified via template arguments. Memory for the matrix is allo
time. This is generally faster than dynamic memory allocation, but the size of the matrix can't be chang
(directly or indirectly).
For convenience, there are several pre‐defined typedefs for each matrix type (where the types are:
cx_fmat, cx_mat). The typedefs specify a square matrix size, ranging from 2x2 to 9x9. The typedefs we
appending a two digit form of the size to the matrix type ‐‐ for example, mat33 is equivalent to
http://arma.sourceforge.net/docs.html 6/202
4/25/2016 Armadillo: C++ linear algebra library
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
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 b
generate a 5x5 matrix with every element equal to 123.0:
mat A(5,5); A = 123.0;
See also:
matrix attributes
accessing elements
initialising elements
math & relational operators
submatrix views
saving & loading matrices
printing matrices
STL‐style element iterators
.eval()
conv_to() (convert between matrix types)
explanation of typedef (cplusplus.com)
Col class
Row class
Cube class
SpMat class (sparse matrix)
config.hpp
http://arma.sourceforge.net/docs.html 7/202
4/25/2016 Armadillo: C++ linear algebra library
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, e
Functions which take Mat as input can generally also take Col as input. Main exceptions are functions which require
Constructors
vec()
vec(n_elem)
vec(n_elem, fill_type)
vec(size(X))
vec(size(X), fill_type)
vec(vec)
vec(mat) (a 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)
When specifying the size with n_elem, by default the memory is uninitialised; memory can be initialised by specify
per the Mat class
Advanced constructors:
Create a column vector using data from writable auxiliary (external) memory, where ptr_aux_mem
memory. By default the vector allocates its own memory and copies data from the auxiliary memory (fo
copy_aux_mem is set to false, the vector will instead directly use the auxiliary memory (ie. no copying)
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 direct
memory)
when strict is set to false, the vector will use the auxiliary memory until a size change
when strict is set to true, the vector will be bound to the auxiliary memory for its lifetime; the nu
the vector can't be changed
the default setting of strict in versions 6.000+ is false
the default setting of strict in versions 5.600 and earlier is true
Create a column vector by copying data from read‐only auxiliary memory, where ptr_aux_mem is a poin
vec::fixed<number_of_elements>
Create a fixed size column vector, with the size specified via the template argument. Memory for the ve
compile time. This is generally faster than dynamic memory allocation, but the size of the vector can't b
afterwards (directly or indirectly).
For convenience, there are several pre‐defined typedefs for each vector type (where the types are:
cx_fvec, cx_vec as well as the corresponding colvec versions). The pre‐defined typedefs specify vector s
to 9. The typedefs were defined by simply appending a single digit form of the size to the vector type ‐‐
equivalent to vec::fixed<3>, while cx_vec4 is equivalent to cx_vec::fixed<4>.
vec::fixed<number_of_elements>(const ptr_aux_mem)
Create a fixed size column vector, with the size specified via the template argument; data is copied fro
where ptr_aux_mem is a pointer to the memory
Examples:
vec x(10);
vec y = zeros<vec>(10);
mat A = randu<mat>(10,10);
vec z = A.col(5); // extract a column vector
http://arma.sourceforge.net/docs.html 8/202
4/25/2016 Armadillo: C++ linear algebra library
Caveat: For mathematical correctness, scalars are treated as 1x1 matrices during initialisation. As such, the code b
generate a column vector with every element equal to 123.0:
vec a(5); a = 123.0;
See also:
element initialisation
Mat class
Row class
http://arma.sourceforge.net/docs.html 9/202
4/25/2016 Armadillo: C++ linear algebra library
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.
Functions which take Mat as input can generally also take Row as input. Main exceptions are functions which requir
Constructors
rowvec()
rowvec(n_elem)
rowvec(n_elem, fill_type)
rowvec(size(X))
rowvec(size(X), fill_type)
rowvec(rowvec)
rowvec(mat) (a 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)
When specifying the size with n_elem, by default the memory is uninitialised; memory can be initialised by specify
per the Mat class
Advanced constructors:
Create a row vector using data from writable auxiliary (external) memory, where ptr_aux_mem is a poin
By default the vector allocates its own memory and copies data from the auxiliary memory (for safety).
copy_aux_mem is set to false, the vector will instead directly use the auxiliary memory (ie. no copying)
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 direct
memory)
when strict is set to false, the vector will use the auxiliary memory until a size change
when strict is set to true, the vector will be bound to the auxiliary memory for its lifetime; the nu
the vector can't be changed
the default setting of strict in versions 6.000+ is false
the default setting of strict in versions 5.600 and earlier is true
Create a row vector by copying data from read‐only auxiliary memory, where ptr_aux_mem is a pointer
rowvec::fixed<number_of_elements>
Create a fixed size row vector, with the size specified via the template argument. Memory for the vecto
compile time. This is generally faster than dynamic memory allocation, but the size of the vector can't b
afterwards (directly or indirectly).
For convenience, there are several pre‐defined typedefs for each vector type (where the types are:
frowvec, rowvec, cx_frowvec, cx_rowvec). The pre‐defined typedefs specify vector sizes ranging from 2
were defined by simply appending a single digit form of the size to the vector type ‐‐ for example,
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 a
where ptr_aux_mem is a pointer to the memory
Examples:
rowvec x(10);
rowvec y = zeros<rowvec>(10);
mat A = randu<mat>(10,10);
rowvec z = A.row(5); // extract a row vector
http://arma.sourceforge.net/docs.html 10/202
4/25/2016 Armadillo: C++ linear algebra library
Caveat: For mathematical correctness, scalars are treated as 1x1 matrices during initialisation. As such, the code b
generate a row vector with every element equal to 123.0:
rowvec r(5); r = 123.0;
See also:
element initialisation
Mat class
Col class
http://arma.sourceforge.net/docs.html 11/202
4/25/2016 Armadillo: C++ linear algebra library
Cube<type>
cube
cx_cube
Classes for cubes, also known as "3D matrices" or 3rd order tensors
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
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 sli
Constructors:
cube()
cube(n_rows, n_cols, n_slices)
cube(n_rows, n_cols, n_slices, fill_type)
cube(size(X))
cube(size(X), fill_type)
cube(cube)
cx_cube(cube, cube) (for constructing a complex cube out of two real cubes)
When specifying the cube size with n_rows, n_cols and n_slices, by default the memory is uninitialised; memory ca
specifying the fill_type, as per the Mat class (except for fill::eye)
Advanced constructors:
Create a fixed size cube, with the size specified via template arguments. Memory for the cube is allocat
This is generally faster than dynamic memory allocation, but the size of the cube can't be changed after
indirectly).
Create a cube using data from writable auxiliary (external) memory, where ptr_aux_mem is a pointer to
default the cube allocates its own memory and copies data from the auxiliary memory (for safety). How
copy_aux_mem is set to false, the cube will instead directly use the auxiliary memory (ie. no copying);
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
memory)
when strict is set to false, the cube will use the auxiliary memory until a size change
when strict is set to true, the cube will be bound to the auxiliary memory for its lifetime; the num
the cube can't be changed
the default setting of strict in versions 6.000+ is false
the default setting of strict in versions 5.600 and earlier is true
Create a cube by copying data from read‐only auxiliary memory, where ptr_aux_mem is a pointer to the
Examples:
cube x(1,2,3);
cube y = randu<cube>(4,5,6);
mat B = randu<mat>(4,5);
y.slice(2) = B; // set a slice in the cube
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);
http://arma.sourceforge.net/docs.html 12/202
4/25/2016 Armadillo: C++ linear algebra library
c.slice(0) = randu<mat>(10,20); // wrong size
For mathematical correctness, scalars are treated as 1x1x1 cubes during initialisation. As such, the code belo
a cube with every element equal to 123.0:
cube c(5,6,7); c = 123.0;
See also:
cube attributes
accessing elements
math & relational operators
subcube views and slices
saving & loading cubes
STL‐style element iterators
field class
Mat class
http://arma.sourceforge.net/docs.html 13/202
4/25/2016 Armadillo: C++ linear algebra library
field<object_type>
Somewhat similar to a matrix or cube, but instead of each element being a scalar, each element can be a vector, o
Each element can have an arbitrary size (eg. in a field of matrices, each matrix can have a different 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
http://arma.sourceforge.net/docs.html 14/202
4/25/2016 Armadillo: C++ linear algebra library
SpMat<type>
sp_mat
sp_cx_mat
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
In this documentation the sp_mat type is used for convenience; it is possible to use other types instead, eg.
Constructors:
sp_mat()
sp_mat(n_rows, n_cols)
sp_mat(size(X))
sp_mat(sp_mat)
sp_mat(mat)
sp_mat(string)
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)
This class behaves in a similar manner to the Mat class, however, member functions which set all elements to non‐z
hence do not make sense for sparse matrices) have been deliberately omitted; examples of omitted functions:
etc.
Using batch insertion constructors is generally much faster than consecutively inserting values using
operators
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
inserted; the location of the i‐th element is specified by the contents of the i‐th column of the location
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
is a dense column vector of type uvec (with length n_cols + 1) containing indices of values correspondin
columns; the vectors correspond to the arrays used by the compressed sparse column format; this form
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 sam
the sparse matrix. For forms 1 and 2, the value in values[i] will be inserted at the location specified by
the locations matrix.
For form 3, add_values is either true or false; when set to true, identical locations are allowed, and the
locations are added
The size of the constructed matrix is either automatically determined from the maximal locations in the
(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 sor
column‐major ordering
If check_for_zeros is set to false, the values vector is assumed to contain no zero values
Caveats:
support for sparse matrices in this version is preliminary
the following subset of operations currently works with sparse matrices:
element access
fundamental arithmetic operations (such as addition and multiplication)
submatrix views (contiguous forms only)
diagonal views
saving and loading (using arma_binary format only)
element‐wise functions: abs(), imag(), real(), conj(), sqrt(), square()
scalar functions of matrices: accu(), as_scalar(), dot(), norm(), trace()
vector valued functions of matrices: min(), max(), nonzeros(), sum(), mean(), var()
matrix valued functions of matrices: diagmat(), join_rows(), join_cols(), repmat(), reshape(), resize()
generated matrices: speye(), spones(), sprandu()/sprandn()
eigen and svd decomposition: eigs_sym(), eigs_gen(), svds()
http://arma.sourceforge.net/docs.html 15/202
4/25/2016 Armadillo: C++ linear algebra library
solution of sparse linear systems: spsolve()
miscellaneous: print()
Examples:
sp_mat A(5,6);
sp_mat B(6,5);
A(0,0) = 1;
A(1,0) = 2;
B(0,0) = 3;
B(0,1) = 4;
sp_mat C = 2*B;
sp_mat D = A*C;
vec values;
values << 1.5 << 3.2 << endr;
See also:
accessing elements
printing matrices
Sparse Matrix in Wikipedia
Mat class (dense matrix)
http://arma.sourceforge.net/docs.html 16/202
4/25/2016 Armadillo: C++ linear algebra library
operators: + − * / % == != <= >= < >
Meanings:
== Element‐wise equality evaluation of two objects; generates a matrix of type umat with entries that indi
given position the two elements from the two objects are equal (1) or not equal (0)
!= Element‐wise non‐equality evaluation of two objects
>= As for ==, but the check is for "greater than or equal to"
<= As for ==, but the check is for "less than or equal to"
Caveat: operators involving an equality comparison (ie. ==, !=, >=, <=) are not recommended for matrices of type
the necessarily limited precision of the underlying element types; you may wish to use approx_equal() instead
If the +, − and % operators are chained, Armadillo will try to avoid the generation of temporaries; no temporaries a
given objects are of the same type and size
If the * operator is chained, Armadillo will try to find an efficient ordering of the matrix multiplications
Examples:
mat A = randu<mat>(5,10);
mat B = randu<mat>(5,10);
mat C = randu<mat>(10,5);
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:
any()
all()
accu()
approx_equal()
as_scalar()
find()
.each_col() & .each_row()
.transform()
miscellaneous element‐wise functions (exp, log, pow, sqrt, square, round, ...)
http://arma.sourceforge.net/docs.html 17/202
4/25/2016 Armadillo: C++ linear algebra library
http://arma.sourceforge.net/docs.html 18/202
4/25/2016 Armadillo: C++ linear algebra library
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
.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()
http://arma.sourceforge.net/docs.html 19/202
4/25/2016 Armadillo: C++ linear algebra library
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 eleme
assumption of a flat layout, with column‐major ordering of data (ie. column by column). A
exception is thrown if the requested element is out of bounds. The bounds check can be
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
debugged.
(i,j) For mat and 2D field classes, access the element/object stored at the i‐th row and j‐th colum
A std::logic_error exception is thrown if the requested element is out of bounds. The bounds
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
debugged.
(i,j,k) For cube and 3D field classes, access the element/object stored at the i‐th row, j‐th column
A std::logic_error exception is thrown if the requested element is out of bounds. The bounds
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 be
debugged.
The bounds checks used by the (n), (i,j) and (i,j,k) access forms can be disabled by defining the ARMA_NO_DEBUG
including the armadillo header file (eg. #define ARMA_NO_DEBUG). Disabling the bounds checks is not recommend
has been thoroughly debugged ‐‐ it's better to write correct code first, and then maximise its speed.
The indices of elements are specified via the uword type, which is a typedef for an unsigned integer type. When us
elements, it's best to use uword instead of int. For example: for(uword i=0; i<X.n_elem; ++i) { X(i) = ... }
Caveat: for sparse matrices, using element access operators to insert values via loops can be inefficient; you may w
insertion constructors instead
Examples:
mat A = randu<mat>(10,10);
A(9,9) = 123.0;
double x = A.at(9,9);
double y = A[99];
vec p = randu<vec>(10,1);
p(9) = 123.0;
double z = p[9];
See also:
.in_range()
element initialisation
submatrix views
.memptr()
iterators (matrices)
iterators (cubes)
config.hpp
http://arma.sourceforge.net/docs.html 20/202
4/25/2016 Armadillo: C++ linear algebra library
element initialisation
When using the C++11 standard, elements in Mat, Col, Row can be set via initialiser lists
When using the old C++98 standard, elements can be set via the << operator; special element endr indicates "end o
similar to std::endl)
Caveat: using the << operator is slower than using initialiser lists
Examples:
// C++11
vec v = { 1, 2, 3 };
// C++98
mat B;
See also:
element access
.reshape()
.print()
saving & loading matrices
advanced constructors (matrices)
http://arma.sourceforge.net/docs.html 21/202
4/25/2016 Armadillo: C++ linear algebra library
.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(5,10); A.zeros(); // or: mat A(5,10,fill::zeros);
mat B; B.zeros(10,20);
See also:
zeros() (standalone function)
.ones()
.randu()
.fill()
.imbue()
.reset()
.set_size()
size()
http://arma.sourceforge.net/docs.html 22/202
4/25/2016 Armadillo: C++ linear algebra library
.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(5,10); A.ones(); // or: mat A(5,10,fill::ones);
mat B; B.ones(10,20);
See also:
ones() (standalone function)
.eye()
.zeros()
.fill()
.imbue()
.randu()
size()
http://arma.sourceforge.net/docs.html 23/202
4/25/2016 Armadillo: C++ linear algebra library
.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 si
dimensions
Examples:
mat A(5,5); A.eye(); // or: mat A(5,5,fill::eye);
mat B; B.eye(5,5);
See also:
.ones()
.diag()
diagmat()
diagvec()
eye() (standalone function)
size()
http://arma.sourceforge.net/docs.html 24/202
4/25/2016 Armadillo: C++ linear algebra library
.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(5,10); A.randu(); // or: mat A(5,10,fill::randu);
mat B; B.randu(10,20);
See also:
randu() & randn() (standalone functions)
.fill()
.imbue()
.ones()
.zeros()
size()
uniform distribution in Wikipedia
normal distribution in Wikipedia
http://arma.sourceforge.net/docs.html 25/202
4/25/2016 Armadillo: C++ linear algebra library
.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,5);
A.fill(123.0);
See also:
.imbue()
.ones()
.zeros()
.randu() & .randn()
constants (pi, nan, inf, ...)
http://arma.sourceforge.net/docs.html 26/202
4/25/2016 Armadillo: C++ linear algebra library
.imbue( functor )
.imbue( lambda_function ) (C++11 only)
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:
// C++11 only example
// need to include <random>
mat A(4,5);
See also:
.fill()
.transform()
function object at Wikipedia
C++11 lambda functions at Wikipedia
lambda function at cprogramming.com
http://arma.sourceforge.net/docs.html 27/202
4/25/2016 Armadillo: C++ linear algebra library
.transform( functor )
.transform( lambda_function ) (C++11 only)
For matrices, transformation is done column‐by‐column (ie. column 0 is transformed, then column 1, ...)
For cubes, transformation is done slice‐by‐slice, with each slice treated as a matrix
Examples:
// C++11 only example
mat A = ones<mat>(4,5);
See also:
.for_each()
.imbue()
.fill()
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
http://arma.sourceforge.net/docs.html 28/202
4/25/2016 Armadillo: C++ linear algebra library
.for_each( functor )
.for_each( lambda_function ) (C++11 only)
For cubes, processing is done slice‐by‐slice, with each slice treated as a matrix
Examples:
// C++11 only examples
mat A = ones<mat>(4,5);
field<mat> F(2,3);
See also:
.transform()
.each_col() & .each_row()
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
http://arma.sourceforge.net/docs.html 29/202
4/25/2016 Armadillo: C++ linear algebra library
.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
If you need to initialise the elements to zero while changing the size, use .zeros() instead
If you need to explicitly preserve data while changing the size, use .reshape() or .resize() instead;
caveat: .reshape() and .resize() are considerably slower than .set_size()
Examples:
mat A; A.set_size(5,10); // or: mat A(5,10);
See also:
.reset()
.copy_size()
.reshape()
.resize()
.zeros()
size()
http://arma.sourceforge.net/docs.html 30/202
4/25/2016 Armadillo: C++ linear algebra library
.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 th
column‐wise manner; the elements in the generated object are placed column‐wise (ie. the first column is filled up
second column)
The layout of the elements in the recreated object will be different to the layout in the previous version of the obj
If the total number of elements in the previous version of the object is less than the specified size, the extra elem
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 subse
taken
Caveats:
do not use .reshape() if you simply want to change the size without preserving data; use .set_size() instead, w
to grow/shrink the object while preserving the elements as well as the layout of the elements, use .resize()
to create a vector representation of a matrix (ie. concatenate all the columns or rows), use vectorise()
Examples:
mat A = randu<mat>(4,5);
A.reshape(5,4);
See also:
.resize()
.set_size()
.copy_size()
.zeros()
.reset()
reshape() (standalone function)
vectorise()
size()
http://arma.sourceforge.net/docs.html 31/202
4/25/2016 Armadillo: C++ linear algebra library
.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 t
Can be used for growing or shrinking an object (ie. adding/removing rows, and/or columns, and/or slices)
Caveat: do not use .resize() if you simply want to change the size without preserving data; use .set_size() instead,
Examples:
mat A = randu<mat>(4,5);
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()
http://arma.sourceforge.net/docs.html 32/202
4/25/2016 Armadillo: C++ linear algebra library
.copy_size( A )
Object A must be of the same root type as the object being modified (eg. you can't set the size of a matrix by prov
Examples:
mat A = randu<mat>(5,6);
mat B;
B.copy_size(A);
See also:
.reset()
.set_size()
.reshape()
.resize()
.zeros()
repmat()
size()
http://arma.sourceforge.net/docs.html 33/202
4/25/2016 Armadillo: C++ linear algebra library
.reset()
Examples:
mat A = randu<mat>(5, 5);
A.reset();
See also:
.set_size()
.is_empty()
.zeros()
http://arma.sourceforge.net/docs.html 34/202
4/25/2016 Armadillo: C++ linear algebra library
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 )
X.unsafe_col( col_number )
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_ind
indices must be of type uvec
The function .unsafe_col() is provided for speed reasons and should be used only if you know what you are doing. I
independent Col vector object (eg. vec), but uses memory from the existing matrix object. As such, the created ve
and does not take into account that the underlying matrix memory could be freed (eg. due to any operation involvi
the matrix).
Examples:
mat A = zeros<mat>(5,10);
A.col(1) = randu<mat>(5,1);
A(span::all, 1) = randu<mat>(5,1);
mat X = randu<mat>(5,5);
X.elem(indices) = ones<vec>(4);
See also:
diagonal views
.each_col() & .each_row() (vector operations repeated on each column or row)
http://arma.sourceforge.net/docs.html 35/202
4/25/2016 Armadillo: C++ linear algebra library
.colptr()
.in_range()
find()
join_rows/columns/slices
shed_rows/columns/slices
.insert_rows/cols/slices
size()
subcube views
http://arma.sourceforge.net/docs.html 36/202
4/25/2016 Armadillo: C++ linear algebra library
subcube views and slices
A collection of member functions of the Cube class that provide subcube views
Q.subcube( first_row, first_col, first_slice, last_row, last_col, last_slice ) related views (docu
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
Examples:
cube A = randu<cube>(2,3,4);
mat B = A.slice(1);
A.slice(0) = randu<mat>(2,3);
A.slice(0)(1,2) = 99.0;
See also:
.in_range()
.each_slice()
join_slices()
shed_slices()
insert_slices()
size()
submatrix views
http://arma.sourceforge.net/docs.html 37/202
4/25/2016 Armadillo: C++ linear algebra library
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
http://arma.sourceforge.net/docs.html 38/202
4/25/2016 Armadillo: C++ linear algebra library
.diag()
.diag( k )
Examples:
mat X = randu<mat>(5,5);
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();
See also:
.eye()
diagvec()
diagmat()
submatrix views
.each_col() & .each_row()
trace()
http://arma.sourceforge.net/docs.html 39/202
4/25/2016 Armadillo: C++ linear algebra library
.each_col()
.each_row()
.each_col( vector_of_indices )
.each_row( vector_of_indices )
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
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 ele
underlying matrix
Examples:
mat X = ones<mat>(6,5);
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:
submatrix views
diagonal views
repmat()
.for_each()
.each_slice()
http://arma.sourceforge.net/docs.html 40/202
4/25/2016 Armadillo: C++ linear algebra library
.each_slice()
.each_slice( vector_of_indices )
.each_slice( lambda_function ) (C++11 only)
If the argument vector_of_indices is specified, it must evaluate to a vector of type uvec; the vector contains a list
slices to be used
If the lambda_function is specified, the function must accept a reference to a Mat object with the same element t
cube
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:
subcube views
.for_each()
.each_col() & .each_row()
http://arma.sourceforge.net/docs.html 41/202
4/25/2016 Armadillo: C++ linear algebra library
.set_imag( X )
.set_real( X )
Examples:
mat A = randu<mat>(4,5);
mat B = randu<mat>(4,5);
cx_mat C = zeros<cx_mat>(4,5);
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 = randu<mat>(4,5);
mat B = randu<mat>(4,5);
cx_mat C = cx_mat(A,B);
See also:
matrix constructors
cube constructors
imag() / real()
http://arma.sourceforge.net/docs.html 42/202
4/25/2016 Armadillo: C++ linear algebra library
.insert_rows( row_number, X ) (member functions of Mat and Col)
.insert_rows( row_number, number_of_rows )
.insert_rows( row_number, number_of_rows, set_to_zero )
Functions with the number_of_... argument: expand the object by creating new rows/columns/slices. By default, t
rows/columns/slices are set to zero. If set_to_zero is false, the memory used by the new rows/columns/slices will
Examples:
mat A = randu<mat>(5,10);
mat B = ones<mat>(5,2);
See also:
shed_rows/columns/slices
join_rows/columns/slices
.resize()
submatrix views
subcube views
http://arma.sourceforge.net/docs.html 43/202
4/25/2016 Armadillo: C++ linear algebra library
.shed_row( row_number ) (member functions of Mat, Col and SpMat)
.shed_rows( first_row, last_row )
Examples:
mat A = randu<mat>(5,10);
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
http://arma.sourceforge.net/docs.html 44/202
4/25/2016 Armadillo: C++ linear algebra library
.swap_rows( row1, row2 )
.swap_cols( col1, col2 )
Examples:
mat X = randu<mat>(5,5);
X.swap_rows(0,4);
See also:
fliplr() & flipud()
.swap()
http://arma.sourceforge.net/docs.html 45/202
4/25/2016 Armadillo: C++ linear algebra library
.swap( X )
Examples:
mat A = zeros<mat>(4,5);
mat B = ones<mat>(6,7);
A.swap(B);
See also:
.swap_rows() & .swap_cols()
http://arma.sourceforge.net/docs.html 46/202
4/25/2016 Armadillo: C++ linear algebra library
.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 = randu<mat>(5,5);
const mat B = randu<mat>(5,5);
See also:
.colptr()
element access
iterators (matrices)
iterators (cubes)
advanced constructors (matrices)
advanced constructors (cubes)
http://arma.sourceforge.net/docs.html 47/202
4/25/2016 Armadillo: C++ linear algebra library
.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
Examples:
mat A = randu<mat>(5,5);
See also:
.memptr()
submatrix views
element access
iterators (matrices)
advanced constructors (matrices)
http://arma.sourceforge.net/docs.html 48/202
4/25/2016 Armadillo: C++ linear algebra library
iterators (matrices & vectors)
STL‐style iterators and associated member functions of Mat, Col, Row and SpMat
Member functions:
.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
.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
Iterator types:
mat::iterator random access iterators, for read/write access to elements (which are stored
vec::iterator
rowvec::iterator
sp_mat::iterator
mat::const_iterator random access iterators, for read‐only access to elements (which are stored c
vec::const_iterator
rowvec::const_iterator
sp_mat::const_iterator
mat::col_iterator random access iterators, for read/write access to the elements of a specific c
vec::col_iterator
rowvec::col_iterator
mat::const_col_iterator random access iterators, for read‐only access to the elements of a specific col
vec::const_col_iterator
rowvec::const_col_iterator
mat::row_iterator rudimentary forward iterator, for read/write access to the elements of a spec
sp_mat::row_iterator
mat::const_row_iterator rudimentary forward iterator, for read‐only access to the elements of a specif
sp_mat::const_row_iterator
vec::row_iterator random access iterators, for read/write access to the elements of a specific ro
rowvec::row_iterator
vec::const_row_iterator random access iterators, for read‐only access to the elements of a specific row
rowvec::const_row_iterator
Examples:
mat X = randu<mat>(5,5);
mat::iterator a = X.begin();
mat::iterator b = X.end();
See also:
STL‐style container functions
iterator at cplusplus.com
element access
.memptr()
.colptr()
submatrix views
http://arma.sourceforge.net/docs.html 49/202
4/25/2016 Armadillo: C++ linear algebra library
iterators (cubes)
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 ord
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 sli
ordered column by column
cube::const_slice_iterator random access iterators, for read‐only access to the elements of a particular sli
Examples:
cube X = randu<cube>(2,3,4);
cube::iterator a = X.begin();
cube::iterator b = X.end();
See also:
iterator at cplusplus.com
element access
http://arma.sourceforge.net/docs.html 50/202
4/25/2016 Armadillo: C++ linear algebra library
STL‐style container functions
Member functions that mimic the containers in the C++ Standard Template Library:
Examples:
mat A = randu<mat>(5,5);
cout << A.size() << endl;
A.clear();
cout << A.empty() << endl;
See also:
iterators (matrices)
matrix and vector attributes
.is_empty()
.reset()
http://arma.sourceforge.net/docs.html 51/202
4/25/2016 Armadillo: C++ linear algebra library
.t()
.st()
Examples:
mat A = randu<mat>(4,5);
mat B = A.t();
See also:
trans()
fliplr() & flipud()
http://arma.sourceforge.net/docs.html 52/202
4/25/2016 Armadillo: C++ linear algebra library
.i()
If the matrix expression appears to be singular, the output matrix is reset and a std::runtime_error exception is thr
Caveats:
if matrix A is know to be symmetric positive definite, it's faster to use inv_sympd() instead
to solve a system of linear equations, such as Z = inv(X)*Y, it is faster and more accurate to use solve()
Examples:
mat A = randu<mat>(4,4);
mat B = randu<mat>(4,1);
mat X = A.i();
mat Y = (A+A).i();
See also:
inv()
rcond()
pinv()
solve()
spsolve()
http://arma.sourceforge.net/docs.html 53/202
4/25/2016 Armadillo: C++ linear algebra library
.min() (member functions of Mat, Col, Row, SpMat, Cube
.max()
With one or more arguments: return the extremum value of an object and store the location of the extremum valu
variable(s)
Examples:
vec v = randu<vec>(10);
uword index;
double min_val = v.min(index);
cout << "index of min value is " << index << endl;
mat A = randu<mat>(5,5);
uword row;
uword col;
double min_val2 = A.max(row,col);
cout << "max value is at " << row << ',' << col << endl;
See also:
min() & max() (standalone functions)
clamp()
running_stat
running_stat_vec
http://arma.sourceforge.net/docs.html 54/202
4/25/2016 Armadillo: C++ linear algebra library
.eval()
This function should be used sparingly and only in cases where it is absolutely necessary; indiscriminate use can ca
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:
Mat class
http://arma.sourceforge.net/docs.html 55/202
4/25/2016 Armadillo: C++ linear algebra library
.in_range( i ) (member of Mat, Col, Row, Cube
.in_range( span(start, end) ) (member of Mat, Col, Row, Cube
.in_range( first_row, first_col, size(X) ) (X is a matrix or field) (member of Mat, Col, Row, SpMat
.in_range( first_row, first_col, size(n_rows, n_cols) ) (member of Mat, Col, Row, SpMat
.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 = randu<mat>(4,5);
See also:
element access
submatrix views
subcube views
subfield views
.set_size()
http://arma.sourceforge.net/docs.html 56/202
4/25/2016 Armadillo: C++ linear algebra library
.is_empty()
Examples:
mat A = randu<mat>(5,5);
cout << A.is_empty() << endl;
A.reset();
cout << A.is_empty() << endl;
See also:
.is_square()
.is_vec()
.is_finite()
.reset()
http://arma.sourceforge.net/docs.html 57/202
4/25/2016 Armadillo: C++ linear algebra library
.is_square()
Returns true if the matrix is square, ie. number of rows is equal to the number of columns
Examples:
mat A = randu<mat>(5,5);
mat B = randu<mat>(6,7);
See also:
.is_empty()
.is_vec()
.is_finite()
http://arma.sourceforge.net/docs.html 58/202
4/25/2016 Armadillo: C++ linear algebra library
.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
Examples:
mat A = randu<mat>(1,5);
mat B = randu<mat>(5,1);
mat C = randu<mat>(5,5);
See also:
.is_empty()
.is_square()
.is_finite()
http://arma.sourceforge.net/docs.html 59/202
4/25/2016 Armadillo: C++ linear algebra library
.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
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, order is checked via absolute values
Examples:
vec a = randu<vec>(10);
vec b = sort(a);
mat A = randu<mat>(10,10);
See also:
sort()
http://arma.sourceforge.net/docs.html 60/202
4/25/2016 Armadillo: C++ linear algebra library
.is_finite()
Returns false if at least one of the elements of the object is non‐finite (±infinity or NaN)
Examples:
mat A = randu<mat>(5,5);
mat B = randu<mat>(5,5);
B(1,1) = datum::inf;
See also:
is_finite() (standalone function)
find_finite()
find_nonfinite()
constants (pi, nan, inf, ...)
http://arma.sourceforge.net/docs.html 61/202
4/25/2016 Armadillo: C++ linear algebra library
.has_inf()
Examples:
mat A = randu<mat>(5,5);
mat B = randu<mat>(5,5);
B(1,1) = datum::inf;
See also:
.has_nan()
.is_finite()
constants (pi, nan, inf, ...)
http://arma.sourceforge.net/docs.html 62/202
4/25/2016 Armadillo: C++ linear algebra library
.has_nan()
Returns true if at least one of the elements of the object is NaN (not‐a‐number)
Examples:
mat A = randu<mat>(5,5);
mat B = randu<mat>(5,5);
B(1,1) = datum::nan;
See also:
.has_inf()
constants (pi, nan, inf, ...)
http://arma.sourceforge.net/docs.html 63/202
4/25/2016 Armadillo: C++ linear algebra library
.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 head
Elements of a field can only be printed if there is an associated operator<< function defined
Examples:
mat A = randu<mat>(5,5);
mat B = randu<mat>(6,6);
A.print();
See also:
.raw_print()
saving & loading matrices
initialising elements
logging of errors and warnings
http://arma.sourceforge.net/docs.html 64/202
4/25/2016 Armadillo: C++ linear algebra library
.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 ‐‐ ie. the user
parameters such as precision, cell width, etc.
If the cell width is set to zero, a space is printed between the elements
Examples:
mat A = randu<mat>(5,5);
cout.precision(11);
cout.setf(ios::fixed);
http://arma.sourceforge.net/docs.html 65/202
4/25/2016 Armadillo: C++ linear algebra library
saving/loading matrices & cubes
.save() will return a bool set to false if the saving process fails
.load() will return a bool set to false if the loading process fails; additionally, the object will be reset so it has no e
auto_detect Used by .load() only: try to automatically detect the file type as one of the formats desc
the default operation.
raw_ascii Numerical data stored in raw ASCII format, without a header. The numbers are separated
number of columns must be the same in each row. Cubes are loaded as one slice. Data w
Matlab/Octave using the ‐ascii option can be read in Armadillo, except for complex numb
numbers are stored in standard C++ notation, which is a tuple surrounded by brackets: eg
indicates 1.24 + 4.56i.
raw_binary Numerical data stored in machine dependent raw binary format, without a header. Matri
have one column, while cubes are loaded to have one slice with one column. The
used to alter the size of the loaded matrix/cube without losing data.
arma_ascii Numerical data stored in human readable text format, with a simple header to speed up
indicates the type of matrix as well as the number of rows and columns. For cubes, the h
specifies the number of slices.
arma_binary Numerical data stored in machine dependent binary format, with a simple header to spe
header indicates the type of matrix as well as the number of rows and columns. For cube
additionally specifies the number of slices. arma_binary is the default file_type for
csv_ascii Numerical data stored in comma separated value (CSV) text format, without a header. Ap
hdf5_binary_trans As per hdf5_binary, but save/load the data with columns transposed to rows (and vice ve
pgm_binary Image data stored in Portable Gray Map (PGM) format. Applicable to Mat only. Saving
matrices is a lossy operation, as each element is copied and converted to an 8 bit represe
matrix should have values in the [0,255] interval, otherwise the resulting image may not
ppm_binary Image data stored in Portable Pixel Map (PPM) format. Applicable to Cube only. Saving
matrices is a lossy operation, as each element is copied and converted to an 8 bit represe
cube/field should have values in the [0,255] interval, otherwise the resulting image may
correctly.
Examples:
mat A = randu<mat>(5,5);
mat B;
B.load("A1.mat"); // automatically detect format type
mat C;
C.load("A2.mat", arma_ascii); // force loading in arma_ascii format
if(status == true)
{
cout << "loaded okay" << endl;
http://arma.sourceforge.net/docs.html 66/202
4/25/2016 Armadillo: C++ linear algebra library
}
else
{
cout << "problem with loading" << endl;
}
See also:
saving/loading fields
http://arma.sourceforge.net/docs.html 67/202
4/25/2016 Armadillo: C++ linear algebra library
saving/loading fields
.save() will return a bool set to false if the saving process fails
.load() will return a bool set to false if the loading process fails; additionally, the field will be reset so it has no ele
Fields with objects of type std::string are saved and loaded as raw text files. The text files do not have a header. E
separated by a whitespace. load() will only accept text files that have the same number of strings on each line. Th
variable lengths.
Other than storing string fields as text files, the following file formats are supported:
auto_detect
.load(): try to automatically detect the field format type as one of the formats described below
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 sepa
resulting field is comprised of the three matrices, with the red, green and blue components in
third matrix, respectively
.save(): saves a field with exactly three matrices of equal size as an image; it is assumed that t
blue components are stored in the first, second and third matrix, respectively; saving int
is a lossy operation, as each matrix element is copied and converted to an 8 bit representation
See also:
saving/loading matrices and cubes
http://arma.sourceforge.net/docs.html 68/202
4/25/2016 Armadillo: C++ linear algebra library
Generated Vectors/Matrices
http://arma.sourceforge.net/docs.html 69/202
4/25/2016 Armadillo: C++ linear algebra library
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:
matrix_type X = eye<matrix_type>( n_rows, n_cols )
matrix_type Y = eye<matrix_type>( size(X) )
Examples:
mat A = eye<mat>(5,5); // or: mat A(5,5,fill::eye);
See also:
.eye() (member function of Mat)
.diag()
ones()
diagmat()
diagvec()
speye()
size()
http://arma.sourceforge.net/docs.html 70/202
4/25/2016 Armadillo: C++ linear algebra library
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)
Usage:
vector_type v = linspace<vector_type>(start, end, N)
Examples:
vec a = linspace<vec>(0, 5, 6);
vec b = linspace<vec>(5, 0, 6);
See also:
regspace()
logspace()
ones()
interp1()
http://arma.sourceforge.net/docs.html 71/202
4/25/2016 Armadillo: C++ linear algebra library
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 includi
Usage:
vector_type v = logspace<vector_type>(A, B, N)
Examples:
vec a = logspace<vec>(0, 5, 6);
vec b = logspace<vec>(5, 0, 6);
See also:
linspace()
regspace()
http://arma.sourceforge.net/docs.html 72/202
4/25/2016 Armadillo: C++ linear algebra library
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<vec>(10);
uvec u = ones<uvec>(11);
mat A = ones<mat>(5,6);
cube Q = ones<cube>(5,6,7);
See also:
.ones() (member function of Mat, Col, Row and Cube)
eye()
linspace()
regspace()
zeros()
randu() & randn()
spones()
size()
http://arma.sourceforge.net/docs.html 73/202
4/25/2016 Armadillo: C++ linear algebra library
randi( n_elem )
randi( n_elem, distr_param(a,b) )
randi( size(X) )
randi( size(X), distr_param(a,b) )
Generate a vector, matrix or cube with the elements set to random integer values in the [a,b] interval
Usage:
vector_type v = randi<vector_type>( n_elem )
vector_type v = randi<vector_type>( n_elem, distr_param(a,b) )
Caveat: to generate a continuous distribution with floating point values (ie. float or double), use randu() or
Examples:
imat A = randi<imat>(5, 6);
See also:
randu() & randn()
randg()
.imbue()
ones()
zeros()
shuffle()
size()
http://arma.sourceforge.net/docs.html 74/202
4/25/2016 Armadillo: C++ linear algebra library
randu( n_elem )
randu( n_rows, n_cols )
randu( n_rows, n_cols, n_slices )
randu( size(X) )
randn( n_elem )
randn( n_rows, n_cols )
randn( n_rows, n_cols, n_slices )
randn( size(X) )
Generate a vector, matrix or cube with the elements set to random floating point values
randn() uses a normal/Gaussian distribution with zero mean and unit variance
Usage:
vector_type v = randu<vector_type>( n_elem )
matrix_type X = randu<matrix_type>( n_rows, n_cols )
matrix_type Y = randu<matrix_type>( size(X) )
cube_type Q = randu<cube_type>( n_rows, n_cols, n_slices )
cube_type R = randu<cube_type>( size(Q) )
Caveat: to generate a matrix with random integer values instead of floating point values, use randi() instead
Examples:
vec v = randu<vec>(5);
mat A = randu<mat>(5,6);
cube Q = randu<cube>(5,6,7);
See also:
.randu() & .randn() (member functions)
randi()
randg()
.imbue()
ones()
zeros()
shuffle()
sprandu() & sprandn()
size()
uniform distribution in Wikipedia
normal distribution in Wikipedia
http://arma.sourceforge.net/docs.html 75/202
4/25/2016 Armadillo: C++ linear algebra library
randg( n_elem )
randg( n_elem, distr_param(a,b) )
randg( size(X) )
randg( size(X), distr_param(a,b) )
Generate a 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)
Usage:
vector_type v = randg<vector_type>( n_elem )
vector_type v = randg<vector_type>( n_elem, distr_param(a,b) )
Examples:
vec v = randg<vec>(100, distr_param(2,1));
See also:
randu() & randn()
randi()
.imbue()
size()
gamma distribution in Wikipedia
http://arma.sourceforge.net/docs.html 76/202
4/25/2016 Armadillo: C++ linear algebra library
regspace( start, end )
regspace( start, delta, end )
Similar in operation to the Matlab/Octave colon operator, ie. start:end and start:delta:end
Usage:
vector_type v = regspace<vector_type>(start, end)
vector_type v = regspace<vector_type>(start, delta, end)
Examples:
vec a = regspace< vec>(0, 9); // 0, 1, ..., 9
uvec b = regspace<uvec>(2, 2, 10); // 2, 4, ..., 10
ivec c = regspace<ivec>(0, ‐1, ‐10); // 0, ‐1, ..., ‐10
Caveat: do not use regpspace() to specify ranges for contiguous submatrix views; use span() instead
See also:
linspace()
logspace()
http://arma.sourceforge.net/docs.html 77/202
4/25/2016 Armadillo: C++ linear algebra library
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 ze
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()
http://arma.sourceforge.net/docs.html 78/202
4/25/2016 Armadillo: C++ linear algebra library
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()
http://arma.sourceforge.net/docs.html 79/202
4/25/2016 Armadillo: C++ linear algebra library
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
http://arma.sourceforge.net/docs.html 80/202
4/25/2016 Armadillo: C++ linear algebra library
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
Examples:
vec A = randu<vec>(5);
mat X = toeplitz(A);
mat Y = circ_toeplitz(A);
See also:
Toeplitz matrix in MathWorld
Toeplitz matrix in Wikipedia
Circulant matrix in Wikipedia
http://arma.sourceforge.net/docs.html 81/202
4/25/2016 Armadillo: C++ linear algebra library
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<vec>(10);
uvec u = zeros<uvec>(11);
mat A = zeros<mat>(5,6);
cube Q = zeros<cube>(5,6,7);
See also:
.zeros() (member function of Mat, Col, Row, SpMat and Cube)
.ones() (member function of Mat, Col, Row and Cube)
ones()
randu() & randn()
size()
http://arma.sourceforge.net/docs.html 82/202
4/25/2016 Armadillo: C++ linear algebra library
Functions of Vectors/Matrices/Cubes
http://arma.sourceforge.net/docs.html 83/202
4/25/2016 Armadillo: C++ linear algebra library
abs( X )
Examples:
mat A = randu<mat>(5,5);
mat B = abs(A);
cx_mat X = randu<cx_mat>(5,5);
mat Y = abs(X);
See also:
conj()
imag() / real()
conv_to()
http://arma.sourceforge.net/docs.html 84/202
4/25/2016 Armadillo: C++ linear algebra library
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()
http://arma.sourceforge.net/docs.html 85/202
4/25/2016 Armadillo: C++ linear algebra library
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
dim=1, return a column vector (of type ucolvec or umat), with each element (0 or 1) indicating whether the c
X has all non‐zero elements
Examples:
vec V = randu<vec>(10);
mat X = randu<mat>(5,5);
// 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()
conv_to() (convert between matrix/vector types)
vectorise()
http://arma.sourceforge.net/docs.html 86/202
4/25/2016 Armadillo: C++ linear algebra library
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
dim=1, return a column vector (of type ucolvec or umat), with each element (0 or 1) indicating whether the c
X has any non‐zero elements
Examples:
vec V = randu<vec>(10);
mat X = randu<mat>(5,5);
// 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()
http://arma.sourceforge.net/docs.html 87/202
4/25/2016 Armadillo: C++ linear algebra library
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 differ
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 = randu<mat>(5,5);
mat B = A + 0.001;
See also:
all()
any()
find()
relational operators
http://arma.sourceforge.net/docs.html 88/202
4/25/2016 Armadillo: C++ linear algebra library
as_scalar( expression )
Evaluate an expression that results in a 1x1 matrix, followed by converting the 1x1 matrix to a pure scalar
If a binary or trinary expression is given (ie. 2 or 3 terms), the function will try to exploit the fact that the result is
using optimised expression evaluations
Examples:
rowvec r = randu<rowvec>(5);
colvec q = randu<colvec>(5);
mat X = randu<mat>(5,5);
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:
accu()
trace()
dot()
norm()
conv_to()
reshape()
resize()
vectorise()
http://arma.sourceforge.net/docs.html 89/202
4/25/2016 Armadillo: C++ linear algebra library
clamp( X, min_val, max_val )
Create a copy of X with each element clamped to be between min_val and max_val
Examples:
mat A = randu<mat>(5,5);
See also:
min() & max()
.min() & .max() (member functions of Mat)
find()
http://arma.sourceforge.net/docs.html 90/202
4/25/2016 Armadillo: C++ linear algebra library
cond( A )
Return the condition number of matrix A (the ratio of the largest singular value to the smallest)
The computation is based on singular value decomposition; if the decomposition fails, a std::runtime_error
Caveat: the rcond() function is faster for providing an estimate of the reciprocal of the condition number
Examples:
mat A = randu<mat>(5,5);
double c = cond(A);
See also:
rcond()
rank()
inv()
solve()
condition number in MathWorld
condition number in Wikipedia
http://arma.sourceforge.net/docs.html 91/202
4/25/2016 Armadillo: C++ linear algebra library
conj( X )
Examples:
cx_mat X = randu<cx_mat>(5,5);
cx_mat Y = conj(X);
See also:
abs()
imag() / real()
trans()
http://arma.sourceforge.net/docs.html 92/202
4/25/2016 Armadillo: C++ linear algebra library
conv_to< type >::from( X )
Convert 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 vecto
Examples:
mat A = randu<mat>(5,5);
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)
http://arma.sourceforge.net/docs.html 93/202
4/25/2016 Armadillo: C++ linear algebra library
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 = randu<vec>(3);
vec b = randu<vec>(3);
vec c = cross(a,b);
See also:
dot()
Cross product in Wikipedia
Cross product in MathWorld
http://arma.sourceforge.net/docs.html 94/202
4/25/2016 Armadillo: C++ linear algebra library
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 (
Examples:
mat A = randu<mat>(5,5);
mat B = cumsum(A);
mat C = cumsum(A, 1);
vec x = randu<vec>(10);
vec y = cumsum(x);
See also:
cumprod()
accu()
sum()
diff()
http://arma.sourceforge.net/docs.html 95/202
4/25/2016 Armadillo: C++ linear algebra library
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
Examples:
mat A = randu<mat>(5,5);
mat B = cumprod(A);
mat C = cumprod(A, 1);
vec x = randu<vec>(10);
vec y = cumprod(x);
See also:
cumsum()
prod()
http://arma.sourceforge.net/docs.html 96/202
4/25/2016 Armadillo: C++ linear algebra library
det( A )
log_det( val, sign, A )
log_det(): find the log determinant, such that the determinant is equal to exp(val)*sign
Examples:
mat A = randu<mat>(5,5);
double x = det(A);
double val;
double sign;
See also:
determinant in MathWorld
determinant in Wikipedia
http://arma.sourceforge.net/docs.html 97/202
4/25/2016 Armadillo: C++ linear algebra library
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 element
Given matrix X, generate a matrix with the k‐th diagonal containing a copy of the k‐th diagonal of X; all other elem
Examples:
mat A = randu<mat>(5,5);
mat B = diagmat(A);
mat C = diagmat(A,1);
vec v = randu<vec>(5);
mat D = diagmat(v);
mat E = diagmat(v,1);
See also:
.diag()
diagvec()
trimatu() / trimatl()
symmatu() / symmatl()
reshape()
vectorise()
http://arma.sourceforge.net/docs.html 98/202
4/25/2016 Armadillo: C++ linear algebra library
diagvec( A )
diagvec( A, k )
Examples:
mat A = randu<mat>(5,5);
vec d = diagvec(A);
See also:
.diag()
diagmat()
trace()
vectorise()
http://arma.sourceforge.net/docs.html 99/202
4/25/2016 Armadillo: C++ linear algebra library
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
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 difference
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
http://arma.sourceforge.net/docs.html 100/202
4/25/2016 Armadillo: C++ linear algebra library
dot( A, B )
cdot( A, B )
norm_dot( A, B )
Examples:
vec a = randu<vec>(10);
vec b = randu<vec>(10);
double x = dot(a,b);
See also:
norm()
as_scalar()
cross()
conj()
http://arma.sourceforge.net/docs.html 101/202
4/25/2016 Armadillo: C++ linear algebra library
eps( X )
Obtain the positive distance of the absolute value of each element of X to the next largest representable floating p
Examples:
mat A = randu<mat>(4,5);
mat B = eps(A);
See also:
datum::eps
Floating‐Point Arithmetic in MathWorld
IEEE Standard for Floating‐Point Arithmetic in Wikipedia
http://arma.sourceforge.net/docs.html 102/202
4/25/2016 Armadillo: C++ linear algebra library
expmat( X )
Caveat: the matrix exponential operation is not the same as applying the exp() function to each element
Examples:
mat A = randu<mat>(5,5);
mat B = expmat(A);
See also:
logmat()
sqrtmat()
miscellaneous element‐wise functions
matrix exponential in Wikipedia
matrix exponential in MathWorld
http://arma.sourceforge.net/docs.html 103/202
4/25/2016 Armadillo: C++ linear algebra library
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
Examples:
mat A = randu<mat>(5,5);
mat B = randu<mat>(5,5);
See also:
all()
any()
approx_equal()
clamp()
find_finite()
find_nonfinite()
find_unique()
nonzeros()
unique()
sort_index()
conv_to() (convert between matrix/vector types)
submatrix views
subcube views
http://arma.sourceforge.net/docs.html 104/202
4/25/2016 Armadillo: C++ linear algebra library
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 = randu<mat>(5,5);
A(1,1) = datum::inf;
See also:
find()
find_nonfinite()
submatrix views
constants (pi, nan, inf, ...)
http://arma.sourceforge.net/docs.html 105/202
4/25/2016 Armadillo: C++ linear algebra library
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 = randu<mat>(5,5);
A(1,1) = datum::inf;
See also:
find()
find_finite()
submatrix views
constants (pi, nan, inf, ...)
http://arma.sourceforge.net/docs.html 106/202
4/25/2016 Armadillo: C++ linear algebra library
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;
See also:
find()
unique()
submatrix views
http://arma.sourceforge.net/docs.html 107/202
4/25/2016 Armadillo: C++ linear algebra library
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 = randu<mat>(5,5);
mat B = fliplr(A);
mat C = flipud(A);
See also:
shift()
.swap_rows() & .swap_cols()
.t()
http://arma.sourceforge.net/docs.html 108/202
4/25/2016 Armadillo: C++ linear algebra library
imag( X )
real( X )
Examples:
cx_mat C = randu<cx_mat>(5,5);
mat A = imag(C);
mat B = real(C);
Caveat: versions 4.4, 4.5 and 4.6 of the GCC C++ compiler have a bug when using the ‐std=c++0x compiler option (
support for C++11); to work around this bug, preface Armadillo's imag() and real() with the arma namespace qualif
arma::imag(C)
See also:
.set_imag() / .set_real()
abs()
conj()
conv_to()
http://arma.sourceforge.net/docs.html 109/202
4/25/2016 Armadillo: C++ linear algebra library
sub = ind2sub( size(n_rows, n_cols), index )
The subscripts are returned in a vector of type uvec; the length of the vector is the same as the number of argume
size() function (ie. either 2 or 3)
Examples:
uvec s = ind2sub( size(4, 5), 6 );
See also:
size()
sub2ind()
element access
http://arma.sourceforge.net/docs.html 110/202
4/25/2016 Armadillo: C++ linear algebra library
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 sett
"lowmem"
The low‐memory algorithm is considerably slower than the greedy algorithm; using the low‐memory algorithm is on
cases where X takes up more than half of available memory (ie. very large X)
Examples:
mat X = randu<mat>(4,5);
mat Y = randu<mat>(20000,30000);
See also:
.t()
trans()
inplace matrix transpose in Wikipedia
http://arma.sourceforge.net/docs.html 111/202
4/25/2016 Armadillo: C++ linear algebra library
is_finite( X )
Examples:
mat A = randu<mat>(5,5);
mat B = randu<mat>(5,5);
B(1,1) = datum::inf;
See also:
.is_finite() (member function of Mat and Cube)
find_finite()
find_nonfinite()
constants (pi, nan, inf, ...)
http://arma.sourceforge.net/docs.html 112/202
4/25/2016 Armadillo: C++ linear algebra library
join_rows( A, B )
join_horiz( A, B )
join_cols( A, B )
join_vert( A, B )
join_rows() and join_horiz(): horizontal concatenation; for two matrices A and B, join each row of A with the corre
matrices A and B must have the same number of rows
join_cols() and join_vert(): vertical concatenation; for two matrices A and B, join each column of A with the corre
B; matrices A and B must have the same number of columns
Examples:
mat A = randu<mat>(4,5);
mat B = randu<mat>(4,6);
mat C = randu<mat>(6,5);
mat X = join_rows(A,B);
mat Y = join_cols(A,C);
See also:
.shed_rows/cols/slices
.insert_rows/cols/slices
submatrix views
http://arma.sourceforge.net/docs.html 113/202
4/25/2016 Armadillo: C++ linear algebra library
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
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
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
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
http://arma.sourceforge.net/docs.html 114/202
4/25/2016 Armadillo: C++ linear algebra library
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
columns) that denotes the tensor product of A and B
Examples:
mat A = randu<mat>(4,5);
mat B = randu<mat>(5,4);
mat K = kron(A,B);
See also:
Kronecker product in MathWorld
Kronecker product in Wikipedia
http://arma.sourceforge.net/docs.html 115/202
4/25/2016 Armadillo: C++ linear algebra library
logmat( X )
Caveat: the matrix logarithm operation is not the same as applying the log() function to each element
Examples:
mat A = randu<mat>(5,5);
cx_mat B = logmat(A);
See also:
expmat()
sqrtmat()
real()
miscellaneous element‐wise functions
matrix logarithm in Wikipedia
http://arma.sourceforge.net/docs.html 116/202
4/25/2016 Armadillo: C++ linear algebra library
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
Examples:
colvec v = randu<colvec>(10,1);
double x = max(v);
mat M = randu<mat>(10,10);
rowvec a = max(M);
rowvec b = max(M,0);
colvec c = max(M,1);
// element‐wise maximum
mat X = randu<mat>(5,6);
mat Y = randu<mat>(5,6);
mat Z = arma::max(X,Y); // use arma:: prefix to distinguish from std::max()
See also:
clamp()
.min() & .max() (member functions of Mat and Cube)
running_stat
running_stat_vec
http://arma.sourceforge.net/docs.html 117/202
4/25/2016 Armadillo: C++ linear algebra library
nonzeros(X)
Examples:
sp_mat A = sprandu<sp_mat>(100, 100, 0.1);
vec a = nonzeros(A);
See also:
find()
unique()
http://arma.sourceforge.net/docs.html 118/202
4/25/2016 Armadillo: C++ linear algebra library
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, while "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 unde
To obtain the zero norm or Hamming norm (ie. the number of non‐zero elements), use this expression: accu
Examples:
vec q = randu<vec>(5);
See also:
normalise()
vectorise()
dot()
vector norm in Wikipedia
vector norm in MathWorld
matrix norm in Wikipedia
matrix norm in MathWorld
http://arma.sourceforge.net/docs.html 119/202
4/25/2016 Armadillo: C++ linear algebra library
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 hav
Examples:
vec A = randu<vec>(10);
vec B = normalise(A);
vec C = normalise(A, 1);
mat X = randu<mat>(5,6);
mat Y = normalise(X);
mat Z = normalise(X, 2, 1);
See also:
norm()
norm_dot()
Normalised vector in MathWorld
Unit vector in Wikipedia
http://arma.sourceforge.net/docs.html 120/202
4/25/2016 Armadillo: C++ linear algebra library
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 = randu<colvec>(10,1);
double x = prod(v);
mat M = randu<mat>(10,10);
rowvec a = prod(M);
rowvec b = prod(M,0);
colvec c = prod(M,1);
See also:
cumprod()
Schur product
http://arma.sourceforge.net/docs.html 121/202
4/25/2016 Armadillo: C++ linear algebra library
rank( X )
rank( X, tolerance )
The computation is based on singular value decomposition; if the decomposition fails, a std::runtime_error
Examples:
mat A = randu<mat>(4,5);
uword r = rank(A);
See also:
cond()
rcond()
svd()
orth()
datum::eps
Rank in MathWorld
Rank in Wikipedia
http://arma.sourceforge.net/docs.html 122/202
4/25/2016 Armadillo: C++ linear algebra library
rcond( A )
Examples:
mat A = randu<mat>(5,5);
double r = rcond(A);
See also:
cond()
rank()
inv()
solve()
http://arma.sourceforge.net/docs.html 123/202
4/25/2016 Armadillo: C++ linear algebra library
repmat( A, num_copies_per_row, num_copies_per_col )
Examples:
mat A = randu<mat>(2, 3);
See also:
.each_col() & .each_row() (vector operations repeated on each column or row)
.copy_size()
reshape()
resize()
http://arma.sourceforge.net/docs.html 124/202
4/25/2016 Armadillo: C++ linear algebra library
reshape( mat, n_rows, n_cols )
reshape( mat, size(X) )
Generate a matrix or cube sized according to given size specifications, whose elements are taken from the given m
column‐wise manner; the elements in the generated object are placed column‐wise (ie. the first column is filled up
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 ge
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 t
object
Caveats:
do not use reshape() if you simply want to change the size without preserving data; use .set_size() instead, w
to grow/shrink a matrix while preserving the elements as well as the layout of the elements, use resize()
to create a vector representation of a matrix (ie. concatenate all the columns or rows), use vectorise()
Examples:
mat A = randu<mat>(10, 5);
mat B = reshape(A, 5, 10);
See also:
.reshape()
.set_size()
resize()
vectorise()
as_scalar()
conv_to()
diagmat()
repmat()
size()
http://arma.sourceforge.net/docs.html 125/202
4/25/2016 Armadillo: C++ linear algebra library
resize( mat, n_rows, n_cols )
resize( mat, size(X) )
Generate a matrix or cube sized according to given size specifications, whose elements as well as the layout of the
from the given matrix/cube
Caveat: do not use resize() if you simply want to change the size without preserving data; use .set_size() instead,
Examples:
mat A = randu<mat>(4, 5);
mat B = resize(A, 7, 6);
See also:
.resize() (member function of Mat and Cube)
.set_size() (member function of Mat and Cube)
reshape()
vectorise()
as_scalar()
conv_to()
repmat()
size()
http://arma.sourceforge.net/docs.html 126/202
4/25/2016 Armadillo: C++ linear algebra library
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
Examples:
mat A = randu<mat>(4,5);
mat B = shift(A, ‐1);
mat C = shift(A, +1);
See also:
shuffle()
fliplr() & flipud()
http://arma.sourceforge.net/docs.html 127/202
4/25/2016 Armadillo: C++ linear algebra library
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 (
Examples:
mat A = randu<mat>(4,5);
mat B = shuffle(A);
See also:
shift()
sort()
randu() / randn()
http://arma.sourceforge.net/docs.html 128/202
4/25/2016 Armadillo: C++ linear algebra library
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/inequali
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
http://arma.sourceforge.net/docs.html 129/202
4/25/2016 Armadillo: C++ linear algebra library
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 (
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 = randu<mat>(10,10);
mat B = sort(A);
See also:
sort_index()
.is_sorted()
shuffle()
randu() / randn()
http://arma.sourceforge.net/docs.html 130/202
4/25/2016 Armadillo: C++ linear algebra library
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 o
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 = randu<vec>(10);
uvec indices = sort_index(q);
See also:
find()
sort()
http://arma.sourceforge.net/docs.html 131/202
4/25/2016 Armadillo: C++ linear algebra library
sqrtmat( X )
Caveat: the square root of a matrix is generally not the same as applying the sqrt() function to each element
Examples:
mat A = randu<mat>(5,5);
cx_mat B = sqrtmat(A);
See also:
expmat()
logmat()
real()
miscellaneous element‐wise functions
square root of a matrix in Wikipedia
http://arma.sourceforge.net/docs.html 132/202
4/25/2016 Armadillo: C++ linear algebra library
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
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
Examples:
colvec v = randu<colvec>(10,1);
double x = sum(v);
mat M = randu<mat>(10,10);
rowvec a = sum(M);
rowvec b = sum(M,0);
colvec c = sum(M,1);
See also:
accu()
cumsum()
trace()
trapz()
mean()
as_scalar()
http://arma.sourceforge.net/docs.html 133/202
4/25/2016 Armadillo: C++ linear algebra library
index = sub2ind( size(n_rows, n_cols), row, col )
Examples:
uword i = sub2ind( size(4, 5), 2, 3 );
See also:
size()
ind2sub()
element access
http://arma.sourceforge.net/docs.html 134/202
4/25/2016 Armadillo: C++ linear algebra library
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 triang
symmatl(A): generate symmetric matrix from square matrix A, by reflecting the lower triangle to the upper triangl
If A is a complex matrix, the reflection uses the complex conjugate of the elements; to disable the complex conjug
false
Examples:
mat A = randu<mat>(5,5);
mat B = symmatu(A);
mat C = symmatl(A);
See also:
diagmat()
trimatu() / trimatl()
Symmetric matrix in Wikipedia
http://arma.sourceforge.net/docs.html 135/202
4/25/2016 Armadillo: C++ linear algebra library
trace( X )
If X is an expression, the function will try to use optimised expression evaluations to calculate only the diagonal ele
Examples:
mat A = randu<mat>(5,5);
double x = trace(A);
See also:
accu()
as_scalar()
.diag()
diagvec()
sum()
http://arma.sourceforge.net/docs.html 136/202
4/25/2016 Armadillo: C++ linear algebra library
trans( A )
strans( A )
Examples:
mat A = randu<mat>(5,10);
mat B = trans(A);
mat C = A.t(); // equivalent to trans(A), but more compact
See also:
.t()
inplace_trans
http://arma.sourceforge.net/docs.html 137/202
4/25/2016 Armadillo: C++ linear algebra library
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
X must be a vector; its length must equal either the number of rows in Y (when dim=0), or the number of columns
Examples:
vec X = linspace<vec>(0, datum::pi, 1000);
vec Y = sin(X);
mat Z = trapz(X,Y);
See also:
sum()
diff()
linspace()
numerical integration in Wikipedia
numerical integration in MathWorld
trapezoidal rule in Wikipedia
http://arma.sourceforge.net/docs.html 138/202
4/25/2016 Armadillo: C++ linear algebra library
trimatu( A )
trimatl( A )
Examples:
mat A = randu<mat>(5,5);
mat U = trimatu(A);
mat L = trimatl(A);
See also:
symmatu() / symmatl()
diagmat()
Triangular matrix in MathWorld
Triangular matrix in Wikipedia
http://arma.sourceforge.net/docs.html 139/202
4/25/2016 Armadillo: C++ linear algebra library
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 out
column vector
Examples:
mat X;
X << 1 << 2 << endr
<< 2 << 3 << endr;
mat Y = unique(X);
See also:
find()
find_unique()
sort()
nonzeros()
http://arma.sourceforge.net/docs.html 140/202
4/25/2016 Armadillo: C++ linear algebra library
vectorise( A )
vectorise( A, dim )
For dim=0, the elements are copied from X column‐wise; equivalent to concatenating all the columns of A
For dim=1, the elements are copied from X row‐wise; equivalent to concatenating all the rows of A
Examples:
mat A = randu<mat>(4, 5);
vec v = vectorise(A);
See also:
reshape()
resize()
as_scalar()
diagvec()
http://arma.sourceforge.net/docs.html 141/202
4/25/2016 Armadillo: C++ linear algebra library
miscellaneous element‐wise functions:
Usage:
matrix_type B = fn(A)
cube_type B = fn(A)
A and B must have the same matrix_type/cube_type
fn(A) is one of:
Examples:
mat A = randu<mat>(5,5);
mat B = exp(A);
See also:
abs()
clamp()
conj()
imag() / real()
.transform() (apply user‐defined function to each element)
expmat()
logmat()
sqrtmat()
trigonometric functions
statistics functions
miscellaneous constants
http://arma.sourceforge.net/docs.html 142/202
4/25/2016 Armadillo: C++ linear algebra library
trigonometric element‐wise functions (cos, sin, tan, ...)
Usage:
matrix_type Y = trig_fn(X)
cube_type Y = trig_fn(X)
X and Y must have the same matrix_type/cube_type
trig_fn is one of:
cos family: cos, acos, cosh, acosh
sin family: sin, asin, sinh, asinh
tan family: tan, atan, tanh, atanh
Examples:
mat X = randu<mat>(5,5);
mat Y = cos(X);
See also:
miscellaneous functions
statistics functions
http://arma.sourceforge.net/docs.html 143/202
4/25/2016 Armadillo: C++ linear algebra library
http://arma.sourceforge.net/docs.html 144/202
4/25/2016 Armadillo: C++ linear algebra library
R = chol( X )
R = chol( X, layout )
chol( R, X )
chol( R, X, layout )
The argument layout is optional; layout is either "upper" or "lower", which specifies whether R is upper or lower tri
Examples:
mat X = randu<mat>(5,5);
mat Y = X.t()*X;
mat R1 = chol(Y);
mat R2 = chol(Y, "lower");
See also:
lu()
qr()
Cholesky decomposition in MathWorld
Cholesky decomposition in Wikipedia
http://arma.sourceforge.net/docs.html 145/202
4/25/2016 Armadillo: C++ linear algebra library
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
mat A = randu<mat>(50,50);
mat B = A.t()*A; // generate a symmetric matrix
vec eigval;
mat eigvec;
cx_mat C = randu<cx_mat>(50,50);
cx_mat D = C.t()*C;
vec eigval2;
cx_mat eigvec2;
See also:
eig_gen()
eig_pair()
svd()
svd_econ()
eigs_sym()
eigen decomposition in MathWorld
eigenvalues & eigenvectors in Wikipedia
divide & conquer eigenvalue algorithm in Wikipedia
http://arma.sourceforge.net/docs.html 146/202
4/25/2016 Armadillo: C++ linear algebra library
cx_vec eigval = eig_gen( X )
eig_gen( eigval, X )
The eigenvalues and corresponding eigenvectors are stored in eigval and eigvec, respectively
Examples:
mat A = randu<mat>(10,10);
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
http://arma.sourceforge.net/docs.html 147/202
4/25/2016 Armadillo: C++ linear algebra library
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*eig
The eigenvalues and corresponding eigenvectors are stored in eigval and eigvec, respectively
Examples:
mat A = randu<mat>(10,10);
mat B = randu<mat>(10,10);
cx_vec eigval;
cx_mat eigvec;
See also:
eig_gen()
eig_sym()
qz()
eigen decomposition in MathWorld
eigenvalues & eigenvectors in Wikipedia
http://arma.sourceforge.net/docs.html 148/202
4/25/2016 Armadillo: C++ linear algebra library
B = inv( A )
inv( B, A )
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)
Caveats:
if matrix A is know to be symmetric positive definite, it's faster to use inv_sympd() instead
if matrix A is know to be diagonal, use inv( diagmat(A) )
to solve a system of linear equations, such as Z = inv(X)*Y, it is faster and more accurate to use solve()
Examples:
mat A = randu<mat>(5,5);
mat B = inv(A);
See also:
.i()
inv_sympd()
rcond()
pinv()
solve()
spsolve()
diagmat()
matrix inverse in MathWorld
invertible matrix in Wikipedia
http://arma.sourceforge.net/docs.html 149/202
4/25/2016 Armadillo: C++ linear algebra library
B = inv_sympd( A )
inv_sympd( B, A )
If A appears to be singular:
B = inv_sympd(A) resets B and throws a std::runtime_error exception
inv_sympd(B,A) resets B and returns a bool set to false (exception is not thrown)
Caveat: to solve a system of linear equations, such as Z = inv(X)*Y, it is faster and more accurate to use solve()
Examples:
mat A = randu<mat>(5,5);
mat B = inv_sympd(AtA);
See also:
inv()
rcond()
pinv()
solve()
eig_sym()
matrix inverse in MathWorld
invertible matrix in Wikipedia
positive definite matrix in MathWorld
positive definite matrix in Wikipedia
http://arma.sourceforge.net/docs.html 150/202
4/25/2016 Armadillo: C++ linear algebra library
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
The second form provides permuted L and U, such that L*U = X; note that in this case L is generally not lower‐trian
Examples:
mat A = randu<mat>(5,5);
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
http://arma.sourceforge.net/docs.html 151/202
4/25/2016 Armadillo: C++ linear algebra library
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
Examples:
mat A = randu<mat>(5,6);
A.row(0).zeros();
A.col(0).zeros();
mat B = null(A);
See also:
orth()
qr()
svd()
rank()
datum::eps
Orthonormal basis in Wikipedia
http://arma.sourceforge.net/docs.html 152/202
4/25/2016 Armadillo: C++ linear algebra library
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
Examples:
mat A = randu<mat>(5,6);
mat B = orth(A);
See also:
null()
qr()
svd()
rank()
datum::eps
Orthonormal basis in Wikipedia
http://arma.sourceforge.net/docs.html 153/202
4/25/2016 Armadillo: C++ linear algebra library
B = pinv( A )
B = pinv( A, tolerance )
B = pinv( A, tolerance, method )
pinv( B, A )
pinv( B, A, tolerance )
pinv( B, A, tolerance, method )
Examples:
mat A = randu<mat>(4,5);
See also:
.i()
inv()
solve()
spsolve()
datum::eps
Pseudoinverse in MathWorld
Moore‐Penrose Matrix Inverse in MathWorld
Moore‐Penrose pseudoinverse in Wikipedia
http://arma.sourceforge.net/docs.html 154/202
4/25/2016 Armadillo: C++ linear algebra library
qr( Q, R, X )
Decomposition of X into an orthogonal matrix Q and a right triangular matrix R, such that Q*R = X
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 = randu<mat>(5,5);
mat Q, R;
qr(Q,R,X);
See also:
qr_econ()
chol()
orth()
orthogonal matrix in Wikipedia
QR decomposition in Wikipedia
QR decomposition in MathWorld
http://arma.sourceforge.net/docs.html 155/202
4/25/2016 Armadillo: C++ linear algebra library
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
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 corres
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 = randu<mat>(6,5);
mat Q, 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
http://arma.sourceforge.net/docs.html 156/202
4/25/2016 Armadillo: C++ linear algebra library
qz( AA, BB, Q, Z, A, B )
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 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
Examples:
mat A = randu<mat>(10,10);
mat B = randu<mat>(10,10);
mat AA;
mat BB;
mat Q;
mat Z;
See also:
schur()
eig_pair()
generalised Schur decomposition in Wikipedia
http://arma.sourceforge.net/docs.html 157/202
4/25/2016 Armadillo: C++ linear algebra library
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:
qz()
eig_gen()
Schur decomposition in MathWorld
Schur decomposition in Wikipedia
http://arma.sourceforge.net/docs.html 158/202
4/25/2016 Armadillo: C++ linear algebra library
X = solve( A, B )
X = solve( A, B, options ) (version 6.300+)
solve( X, A, B )
solve( X, A, B, options ) (version 6.300+)
Solve a dense system of linear equations, A*X = B, where X is unknown; similar functionality to the \ operator in Ma
X=A\B
Options can be combined using the + operator; for example: solve_opts::fast + solve_opts::no_approx
If A is known to be a triangular matrix, the solution can be computed faster by explicitly indicating that A is triang
trimatu() or trimatl();
indicating a triangular matrix also implies that solve_opts::fast is enabled
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 = randu<mat>(5,5);
vec b = randu<vec>(5);
mat B = randu<mat>(5,5);
vec x2;
bool status = solve(x2, A, b);
See also:
inv()
pinv()
rcond()
syl()
spsolve()
linear system of equations in MathWorld
system of linear equations in Wikipedia
http://arma.sourceforge.net/docs.html 159/202
4/25/2016 Armadillo: C++ linear algebra library
vec s = svd( X )
svd( vec s, X )
Examples:
mat X = randu<mat>(5,5);
mat U;
vec s;
mat V;
svd(U,s,V,X);
See also:
svd_econ()
eig_gen()
eig_sym()
svds()
singular value decomposition in Wikipedia
singular value decomposition in MathWorld
http://arma.sourceforge.net/docs.html 160/202
4/25/2016 Armadillo: C++ linear algebra library
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 = randu<mat>(4,5);
mat U;
vec s;
mat V;
svd_econ(U, s, V, X);
See also:
svd()
eig_gen()
eig_sym()
svds()
singular value decomposition in Wikipedia
singular value decomposition in MathWorld
http://arma.sourceforge.net/docs.html 161/202
4/25/2016 Armadillo: C++ linear algebra library
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 = randu<mat>(5,5);
mat B = randu<mat>(5,5);
mat C = randu<mat>(5,5);
mat X2;
syl(X2, A, B, C);
See also:
solve()
Sylvester equation in Wikipedia
http://arma.sourceforge.net/docs.html 162/202
4/25/2016 Armadillo: C++ linear algebra library
http://arma.sourceforge.net/docs.html 163/202
4/25/2016 Armadillo: C++ linear algebra library
vec eigval = eigs_sym( X, k )
vec eigval = eigs_sym( X, k, form )
vec eigval = eigs_sym( X, k, form, tol )
eigs_sym( eigval, X, k )
eigs_sym( eigval, X, k, form )
eigs_sym( eigval, X, k, form, tol )
Obtain a limited number of eigenvalues and eigenvectors of sparse symmetric real matrix X
The eigenvalues and corresponding eigenvectors are stored in eigval and eigvec, respectively
Examples:
// generate sparse matrix
sp_mat A = sprandu<sp_mat>(1000, 1000, 0.1);
sp_mat B = A.t()*A;
vec eigval;
mat eigvec;
See also:
eigs_gen()
eig_sym()
svds()
eigen decomposition in MathWorld
eigenvalues & eigenvectors in Wikipedia
http://arma.sourceforge.net/docs.html 164/202
4/25/2016 Armadillo: C++ linear algebra library
cx_vec eigval = eigs_gen( X, k )
cx_vec eigval = eigs_gen( X, k, form )
cx_vec eigval = eigs_gen( X, k, form, tol )
eigs_gen( eigval, X, k )
eigs_gen( eigval, X, k, form )
eigs_gen( eigval, X, k, form, tol )
Obtain a limited number of eigenvalues and eigenvectors of sparse general (non‐symmetric/non‐hermitian) square
The eigenvalues and corresponding eigenvectors are stored in eigval and eigvec, respectively
Examples:
// generate sparse matrix
sp_mat A = sprandu<sp_mat>(1000, 1000, 0.1);
cx_vec eigval;
cx_mat eigvec;
See also:
eigs_sym()
eig_gen()
svds()
eigen decomposition in MathWorld
eigenvalues & eigenvectors in Wikipedia
http://arma.sourceforge.net/docs.html 165/202
4/25/2016 Armadillo: C++ linear algebra library
X = spsolve( A, B )
X = spsolve( A, B, solver )
X = spsolve( A, B, solver, settings )
spsolve( X, A, B )
spsolve( X, A, B, solver )
spsolve( X, A, B, solver, settings )
Solve a sparse system of linear equations, A*X = B, where A is a sparse matrix, B is a dense matrix or vector, and
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
usage
equilibrate is either true or false; it indicates whether to equilibrate the system (scale the rows and columns
norm)
symmetric is either true or false; it indicates whether to use SuperLU symmetric mode, which gives preferenc
pivot_threshold is in the range [0.0, 1.0], used for determining whether a diagonal entry is an acceptable piv
SuperLU documentation)
superlu_opts::REF_NONE no refinement
superlu_opts::REF_SINGLE iterative refinement in single precision
superlu_opts::REF_DOUBLE iterative refinement in double precision
superlu_opts::REF_EXTRA iterative refinement in extra precision
Examples:
sp_mat A = sprandu<sp_mat>(1000, 1000, 0.1);
vec b = randu<vec>(1000);
mat B = randu<mat>(1000, 5);
superlu_opts settings;
settings.permutation = superlu_opts::NATURAL;
settings.refine = superlu_opts::REF_NONE;
See also:
solve()
SuperLU home page
linear system of equations in MathWorld
system of linear equations in Wikipedia
http://arma.sourceforge.net/docs.html 166/202
4/25/2016 Armadillo: C++ linear algebra library
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 of sparse matrix X
The singular values are calculated via sparse eigen decomposition of:
⎡ zeros(X.n_rows, X.n_rows) X ⎤
⎣ X.t() zeros(X.n_cols, X.n_cols) ⎦
Caveat: svds() is intended only for finding a few singular values from a large sparse matrix; to find all singular valu
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
http://arma.sourceforge.net/docs.html 167/202
4/25/2016 Armadillo: C++ linear algebra library
http://arma.sourceforge.net/docs.html 168/202
4/25/2016 Armadillo: C++ linear algebra library
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
http://arma.sourceforge.net/docs.html 169/202
4/25/2016 Armadillo: C++ linear algebra library
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()
Convolution in MathWorld
Convolution in Wikipedia
Kernel (image processing) in Wikipedia
http://arma.sourceforge.net/docs.html 170/202
4/25/2016 Armadillo: C++ linear algebra library
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 = randu<vec>(100);
cx_vec Y = fft(X, 128);
See also:
fft2()
conv()
real()
fast Fourier transform in MathWorld
fast Fourier transform in Wikipedia
http://arma.sourceforge.net/docs.html 171/202
4/25/2016 Armadillo: C++ linear algebra library
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 versi
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 = randu<mat>(100,100);
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
http://arma.sourceforge.net/docs.html 172/202
4/25/2016 Armadillo: C++ linear algebra library
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 valu
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:
linspace()
conv()
http://arma.sourceforge.net/docs.html 173/202
4/25/2016 Armadillo: C++ linear algebra library
http://arma.sourceforge.net/docs.html 174/202
4/25/2016 Armadillo: C++ linear algebra library
mean, median, stddev, var
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 )
⎭
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 }
Examples:
mat A = randu<mat>(5,5);
mat B = mean(A);
mat C = var(A);
double m = mean(mean(A));
vec v = randu<vec>(5);
double x = var(v);
See also:
cov()
cor()
diff()
hist()
histc()
running_stat ‐ class for running statistics of scalars
running_stat_vec ‐ class for running statistics of vectors
gmm_diag ‐ class for modelling data as a Gaussian mixture model
kmeans()
http://arma.sourceforge.net/docs.html 175/202
4/25/2016 Armadillo: C++ linear algebra library
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
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
estimation of the covariance matrix (if the observations are from a normal distribution). Using norm_type=1
done using N, which provides the second moment matrix of the observations about their mean
Examples:
mat X = randu<mat>(4,5);
mat Y = randu<mat>(4,5);
mat C = cov(X,Y);
mat D = cov(X,Y, 1);
See also:
cor()
statistics functions
running_stat_vec
Covariance in MathWorld
http://arma.sourceforge.net/docs.html 176/202
4/25/2016 Armadillo: C++ linear algebra library
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
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 obs
norm_type=1 causes normalisation to be done using N
Examples:
mat X = randu<mat>(4,5);
mat Y = randu<mat>(4,5);
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
http://arma.sourceforge.net/docs.html 177/202
4/25/2016 Armadillo: C++ linear algebra library
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
counts
For matrix X, produce a umat matrix containing either column histogram counts (for dim=0, default), or row histog
dim=1)
The bin centers can be automatically determined from the data, with the number of bins specified via n_bins
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 incre
0.1, 0.2, 0.3, ...)
Examples:
vec v = randn<vec>(1000); // Gaussian distribution
See also:
histc()
statistics functions
conv_to()
http://arma.sourceforge.net/docs.html 178/202
4/25/2016 Armadillo: C++ linear algebra library
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 th
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 histog
dim=1)
The edges vector must contain monotonically increasing values (eg. 0.1, 0.2, 0.3, ...)
Examples:
vec v = randn<vec>(1000); // Gaussian distribution
See also:
hist()
statistics functions
conv_to()
http://arma.sourceforge.net/docs.html 179/202
4/25/2016 Armadillo: C++ linear algebra library
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 = randu<mat>(5,4);
mat coeff;
mat score;
vec latent;
vec tsquared;
See also:
principal components analysis in Wikipedia
principal components analysis in MathWorld
http://arma.sourceforge.net/docs.html 180/202
4/25/2016 Armadillo: C++ linear algebra library
running_stat<type>
Class for keeping the running statistics of a continuously sampled one dimensional process/signal
Useful if the storage of individual samples (scalars) is not required, or the number of samples is not known beforeh
For the .var() and .stddev() functions, the default norm_type=0 performs normalisation using N‐1 (where N
far), providing the best unbiased estimator; using norm_type=1 causes normalisation to be done using N, which pro
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:
statistics functions
running_stat_vec
http://arma.sourceforge.net/docs.html 181/202
4/25/2016 Armadillo: C++ linear algebra library
running_stat_vec<vec_type>
running_stat_vec<vec_type>(calc_cov)
Class for keeping the running statistics of a continuously sampled multi‐dimensional process/signal
Useful if the storage of individual samples (vectors) is not required, or if the number of samples is not known befor
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 calc
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
far), providing the best unbiased estimator; using norm_type=1 causes normalisation to be done using N, which pro
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:
cov()
cor()
running_stat
statistics functions
gmm_diag
http://arma.sourceforge.net/docs.html 182/202
4/25/2016 Armadillo: C++ linear algebra library
kmeans( means, data, k, seed_mode, n_iter, print_mode )
The means parameter is the output matrix containing the resulting means, with each mean stored as a column vect
The data parameter is the input data matrix, with each sample stored as a column vector
The seed_mode parameter specifies how the initial means are seeded prior to running k‐means; it is one of:
keep_existing use the means 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)
The n_iter parameter specifies the number of iterations of the k‐means algorithm; a sufficient number of iteration
10
The print_mode parameter is either true or false, indicating whether progress is printed during clustering
If the k‐means algorithm fails, the means matrix is reset and a bool set to false is returned
The k‐means algorithm will run faster on multi‐core machines when OpenMP is enabled in your compiler (eg.
Caveats:
the number of data vectors (number of columns in the data matrix) should be much larger than k (number of
seeding the initial means with static_spread and random_spread can be much more time consuming than with
random_subset
Examples:
uword d = 5; // dimensionality
uword N = 10000; // number of vectors
mat means;
if(status == false)
{
cout << "k‐means failed" << endl;
}
means.print("means:");
See also:
gmm_diag
statistics functions
running_stat_vec
k‐means clustering in Wikipedia
k‐means clustering in MathWorld
OpenMP in Wikipedia
http://arma.sourceforge.net/docs.html 183/202
4/25/2016 Armadillo: C++ linear algebra library
gmm_diag
Class for modelling data as a Gaussian Mixture Model (GMM), under the assumption of diagonal covariance matrices
Provides associated parameter estimation algorithms: k‐means clustering and Expectation‐Maximisation (EM)
The k‐means and EM algorithms are parallelised (multi‐threaded) when compiling with OpenMP enabled (eg. the
gcc)
For an instance of gmm_diag named as M, the member functions and variables are:
M.log_p(X) return a row vector (of type rowvec) containing log‐likelihoods of each colu
X
M.log_p(X, g) return a row vector (of type rowvec) containing log‐likelihoods of each colu
X, according to Gaussian g
M.avg_log_p(X) return a scalar representing the average log‐likelihood of all column vecto
M.avg_log_p(X, g) return a scalar representing the average log‐likelihood of all column vecto
according to Gaussian g
M.assign(V, dist_mode) return the index of the closest mean (or Gaussian) to vector V;
dist_mode is one of:
eucl_dist Euclidean distance (takes only means into account)
prob_dist probabilistic "distance", defined as the inverse likelihood (take
means, covariances and hefts)
M.assign(X, dist_mode) return a row vector containing the indices of the closest means (or Gaussia
vector in matrix X
M.raw_hist(X, dist_mode) return a row vector (of type urowvec) representing the raw histogram of co
the number of counts corresponding to a Gaussian; each count is the numb
corresponding Gaussian was the closest to each column vector in matrix
dist_mode is either eucl_dist or prob_dist (as per the .assign() function abo
M.norm_hist(X, dist_mode) return a row vector (of type rowvec) containing normalised counts;
M.reset(n_dims, n_gaus) set the model to have dimensionality n_dims, with n_gaus number of Gaus
all the means are set to zero, all diagonal covariances are set to one, and
(weights) are set to be uniform
M.means read‐only matrix containing the means (centroids), stored as column vecto
M.dcovs read‐only matrix containing the diagonal covariance matrices, stored as co
M.hefts read‐only row vector containing the hefts (weights)
http://arma.sourceforge.net/docs.html 184/202
4/25/2016 Armadillo: C++ linear algebra library
model
M.set_hefts(V) set the hefts (weights) of the model to be as specified in row vector
the number of hefts must match the existing model
data matrix containing training samples; each sample is stored as a column vector
dist_mode specifies the distance used during the seeding of initial means and k‐means clustering:
eucl_dist Euclidean distance
maha_dist
Mahalanobis distance, which uses a global diagonal covariance matrix estimated fro
samples
seed_mode specifies how the initial means are seeded prior to running k‐means and/or EM algorithms:
keep_existing keep the existing model (do not modify the means, covariances and hefts)
static_subset a subset of the training samples (repeatable)
random_subset a subset of the training samples (random)
static_spread a maximally spread subset of training samples (repeatable)
random_spread a maximally spread subset of training samples (random start)
var_floor the variance floor (smallest allowed value) for the diagonal covariances
print_mode either true or false; enable or disable printing of progress during the k‐means and EM algorithm
Notes:
for probabilistic applications, better model parameters are typically learned with dist_mode set to maha_dist
for vector quantisation applications, model parameters should be learned with dist_mode set to eucl_dist
iterations set to zero
the number of training samples should be much larger than the number of Gaussians
seeding the initial means with static_spread and random_spread can be much more time consuming than with
random_subset
the k‐means and EM algorithms will run faster on multi‐core machines when OpenMP is enabled in your compi
GCC)
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)
{
http://arma.sourceforge.net/docs.html 185/202
4/25/2016 Armadillo: C++ linear algebra library
cout << "learning failed" << endl;
}
model.means.print("means:");
model.save("my_model.gmm");
See also:
statistics functions
running_stat_vec
kmeans()
diagmat()
Mahalanobis distance in Wikipedia
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 Wolfram
vector quantisation in Wikipedia
OpenMP in Wikipedia
http://arma.sourceforge.net/docs.html 186/202
4/25/2016 Armadillo: C++ linear algebra library
Miscellaneous
http://arma.sourceforge.net/docs.html 187/202
4/25/2016 Armadillo: C++ linear algebra library
constants (pi, inf, speed of light, ...)
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 given number x is finite, use is_finite
The physical constants were mainly taken from NIST 2014 CODATA values, and some from WolframAlpha (as of 2009
Examples:
cout << "2.0 * pi = " << 2.0 * datum::pi << endl;
See also:
is_finite()
http://arma.sourceforge.net/docs.html 188/202
4/25/2016 Armadillo: C++ linear algebra library
.fill()
NaN in Wikipedia
physical constant in Wikipedia
std::numeric_limits
http://arma.sourceforge.net/docs.html 189/202
4/25/2016 Armadillo: C++ linear algebra library
wall_clock
Simple wall clock timer class for measuring the number of elapsed seconds
Examples:
wall_clock timer;
mat A = randu<mat>(100,100);
mat B = randu<mat>(100,100);
mat C;
timer.tic();
double n = timer.toc();
http://arma.sourceforge.net/docs.html 190/202
4/25/2016 Armadillo: C++ linear algebra library
logging of warnings and errors
set_stream_err1( user_stream )
set_stream_err2( user_stream )
std::ostream& x = get_stream_err1()
std::ostream& x = get_stream_err2()
By default, warnings and messages associated with exceptions are printed to the std::cout stream
the printing can be disabled by defining ARMA_DONT_PRINT_ERRORS before including the armadillo header
detailed information about errors is always reported via the base std::exception class
set_stream_err1(): change the stream for messages associated with std::logic_error exceptions (eg. out of bounds
set_stream_err2(): change the stream for warnings and messages associated with std::runtime_error and
(eg. failed decompositions, out of memory)
get_stream_err1(): get a reference to the stream for messages associated with std::logic_error exceptions
get_stream_err2(): get a reference to the stream for warnings and messages associated with std::runtime_error
Examples:
// print "hello" to the current err1 stream
get_stream_err1() << "hello" << endl;
Caveat: set_stream_err1() and set_stream_err2() will not change the stream used by .print()
See also:
config.hpp
.print()
std::cout
std::ostream
std::exception
std::logic_error
std::runtime_error
tutorial on exceptions
http://arma.sourceforge.net/docs.html 191/202
4/25/2016 Armadillo: C++ linear algebra library
uword, sword
uword is a typedef for an unsigned integer type; it is used for matrix indices as well as all internal counters and loo
The width can also be forcefully set to 64 bits by enabling ARMA_64BIT_WORD via editing include/armadillo_bits/c
See also:
C++ variable types
explanation of typedef
imat & umat matrix types
ivec & uvec vector types
http://arma.sourceforge.net/docs.html 192/202
4/25/2016 Armadillo: C++ linear algebra library
cx_double, cx_float
Example:
cx_mat X = randu<cx_mat>(5,5);
See also:
complex numbers in the standard C++ library
explanation of typedef
cx_mat matrix type
cx_vec vector type
http://arma.sourceforge.net/docs.html 193/202
4/25/2016 Armadillo: C++ linear algebra library
Examples of Matlab/Octave syntax and conceptually corresponding Armadillo syntax
A(:, k) A.col(k) this is a conceptual example only; exact conversion from Matlab
Armadillo syntax will require taking into account that indexing s
A(k, :) A.row(k)
A(:, p:q) A.cols(p, q)
A(p:q, :) A.rows(p, q)
A(p:q, r:s) A( span(p,q), span(r,s) ) A( span(first_row, last_row), span(first_col, last_col) )
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 = [ 1 2; 3 4; ] A << 1 << 2 << endr element initialisation, with special element endr indicating
<< 3 << 4 << endr;
X = A(:) X = vectorise(A)
X=[A B] X = join_horiz(A,B)
X = [ A; B ] X = join_vert(A,B)
save ‐ascii 'A.dat' A A.save("A.dat", raw_ascii); Matlab/Octave matrices saved as ascii are readable by Armadillo
load ‐ascii 'A.dat' A.load("A.dat", raw_ascii);
http://arma.sourceforge.net/docs.html 194/202
4/25/2016 Armadillo: C++ linear algebra library
example program
#include <iostream>
#include <armadillo>
int main()
{
mat A = randu<mat>(4,5);
mat B = randu<mat>(4,5);
return 0;
}
If you save the above program as example.cpp, under Linux and Mac OS X it can be compiled using:
g++ example.cpp ‐o example ‐O2 ‐larmadillo
As Armadillo is a template library, we strongly recommend to enable optimisation when compiling programs (eg. w
GCC or clang, use the ‐O2 or ‐O3 options)
See also the example program that comes with the Armadillo archive
http://arma.sourceforge.net/docs.html 195/202
4/25/2016 Armadillo: C++ linear algebra library
config.hpp
Armadillo can be configured via editing the file include/armadillo_bits/config.hpp. Specific functionality can be en
uncommenting or commenting out a particular #define, listed below.
ARMA_USE_LAPACK Enable the use of LAPACK, or a high‐speed replacement for LAPACK (eg. Intel MKL, AMD ACM
framework). Armadillo requires LAPACK for functions such as svd(), inv(), eig_sym()
ARMA_USE_BLAS Enable the use of BLAS, or a high‐speed replacement for BLAS (eg. OpenBLAS, Intel MKL, AM
Accelerate framework). BLAS is used for matrix multiplication. Without BLAS, Armadillo wi
matrix multiplication routine, which might be slower for large matrices.
ARMA_USE_ARPACK Enable the use of ARPACK, or a high‐speed replacement for ARPACK. Armadillo requires ARP
decomposition of sparse matrices, ie. eigs_gen(), eigs_sym() and svds()
ARMA_USE_SUPERLU Enable the use of SuperLU, which is used by spsolve() for finding the solutions of sparse sys
versions 4.x are supported. You will need to link with the superlu library (eg. ‐lsuperlu)
ARMA_USE_HDF5 Enable the ability to save and load matrices stored in the HDF5 format; the hdf5.h header
available on your system and you will need to link with the hdf5 library (eg. ‐lhdf5)
ARMA_DONT_USE_WRAPPER Disable going through the run‐time Armadillo wrapper library (libarmadillo.so) when calling
ARPACK, SuperLU and HDF5 functions. You will need to directly link with LAPACK, BLAS, etc
ARMA_USE_CXX11 Use C++11 features, such as initialiser lists; automatically enabled when using a compiler in
example, g++ ‐std=c++11
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). Enable
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_TBB_ALLOC Use Intel TBB scalable_malloc() and scalable_free() instead of standard malloc() and
matrix memory
ARMA_USE_MKL_ALLOC Use Intel MKL mkl_malloc() and mkl_free() instead of standard malloc() and free() for man
memory
ARMA_64BIT_WORD Use 64 bit integers. Automatically enabled when using a C++11 compiler (as of Armadillo 5.
require matrices/vectors capable of holding more than 4 billion elements. Your machine an
have support for 64 bit integers (eg. via "long" or "long long"). This can also be enabled by a
#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 yo
sure that your code runs correctly! We strongly recommend to have the run‐time checks en
development, as this greatly aids in finding mistakes in your code, and hence speeds up de
recommend that run‐time checks be disabled only for the shipped version of your program
build).
ARMA_EXTRA_DEBUG Print out the trace of internal functions used for evaluating expressions. Not recommended
is mainly useful for debugging the library.
ARMA_MAT_PREALLOC The number of pre‐allocated elements used by matrices and vectors. Must be always enabl
integer that is at least 1. By default set to 16. If you mainly use lots of very small vectors (
change the number to the size of your vectors.
ARMA_DEFAULT_OSTREAM The default stream used for printing error messages and by .print(). Must be always enable
http://arma.sourceforge.net/docs.html 196/202
4/25/2016 Armadillo: C++ linear algebra library
defined to std::cout
See also:
logging of warnings and errors
element access
element initialisation
uword/sword
http://arma.sourceforge.net/docs.html 197/202
4/25/2016 Armadillo: C++ linear algebra library
History of API Additions, Changes and Deprecations
Armadillo's version number is A.B.C, where A is a major version, B is a minor version, and C is the patch level (indic
Within each major version (eg. 4.x), minor versions are backwards compatible with earlier minor versions. For exam
for version 4.000 will work with version 4.100, 4.120, 4.200, etc. However, as each minor version may have more fe
extensions) than earlier versions, code specifically written for version 4.100 doesn't necessarily work with 4.000
We don't like changes to existing APIs and strongly prefer not to break any user software. However, to allow evoluti
right to alter the APIs in future major versions of Armadillo while remaining backwards compatible in as many case
version 5.x may have slightly different APIs than 4.x). In a rare instance the user API may need to be tweaked if a b
requires it
This policy is applicable to the APIs described in this documentation; it is not applicable to internal functions (ie. t
internal implementation details may change across consecutive minor versions)
Version 6.700:
added logmat() for calcuating 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
added trapz() for numerical integration
expanded .save() and .load() with hdf5_binary_trans file type, to save/load data with columns transposed to
Version 6.600:
expanded sum(), mean(), min(), max() to handle cubes
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
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()
http://arma.sourceforge.net/docs.html 198/202
4/25/2016 Armadillo: C++ linear algebra library
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 eff
use of 64 bit integers is automatically enabled when using a C++11 compiler
Version 4.650:
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
http://arma.sourceforge.net/docs.html 199/202
4/25/2016 Armadillo: C++ linear algebra library
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
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(),
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()
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::z
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+ wit
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; see also the associated frequently asked questions about th
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
http://arma.sourceforge.net/docs.html 200/202
4/25/2016 Armadillo: C++ linear algebra library
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()
faster generation of random numbers (eg. randu() and randn()), via an algorithm that produces slightly differ
2.x
support for tying writable auxiliary (external) memory to fixed size matrices has been removed; instead, you
matrices with writable auxiliary memory, or initialise fixed size matrices by copying the memory; using auxili
standard matrices is unaffected
.print_trans() and .raw_print_trans() have been removed; instead, you can chain .t() and .print() to achieve
X.t().print()
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 AR
include/armadillo_bits/config.hpp
added experimental support for C++11 initialiser lists, enabled via ARMA_USE_CXX11 in include/armadillo_bit
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
types are equivalent (ie. unsigned integer type with a minimum width 32 bits); however, when the use of 64 b
via ARMA_64BIT_WORD in include/armadillo_bits/config.hpp, the uword type then has a minimum width of 6
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 retu
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()
added standalone is_finite()
.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 indica
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
http://arma.sourceforge.net/docs.html 201/202
4/25/2016 Armadillo: C++ linear algebra library
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
a different interval
In versions earlier than 0.9.0, some multiplication operations directly converted result matrices with a size of
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
as_scalar() wrapping function
Almost all functions have been placed in the delayed operations framework (for speed purposes). This may af
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
assumed to be a directly accessible matrix. The queued operations are executed when the output needs to be
eg. mat B = trans(A) or mat B(trans(A)). If you need to force the execution of the delayed operations, place t
function inside the corresponding Mat constructor. For example, if your code assumed that the output of som
pure matrix, eg. chol(m).diag(), change the code to mat(chol(m)).diag(). Similarly, if you need to pass the re
such as A+B to one of your own functions, use my_function( mat(A+B) ).
http://arma.sourceforge.net/docs.html 202/202