Preamble
-
If something needs to be clarified or fixed in this documentation,
the developers are interested in hearing about it.
-
To aid the conversion of Matlab/Octave programs,
there is a syntax conversion table.
-
First time users may want to have a look at a short example program.
-
There is a small but important API change from earlier versions of Armadillo (< 0.9.x).
Previously, some multiplication operations directly converted result matrices with a size of 1x1 into scalars.
This is no longer the case.
If you know the result of an expression will be a 1x1 matrix and wish to treat it as a pure scalar,
use the as_scalar() wrapping function.
[index]
Matrix, Vector, Cube and Field Classes
Member Functions & Variables
Other Classes
Generated Vectors/Matrices/Cubes
Functions Individually Applied to Each Element of a Matrix/Cube
Scalar Valued Functions of Vectors/Matrices/Cubes
Scalar/Vector Valued Functions of Vectors/Matrices
Vector/Matrix/Cube Valued Functions of Vectors/Matrices/Cubes
Decompositions, Inverse and Related Functions
Miscellaneous
Matrix, Vector, Cube and Field Classes
Mat<type>
mat
cx_mat
-
The root template matrix class is Mat<type>, where type can be one of:
char, int, float, double, std::complex<double>, etc.
-
For convenience the following typedefs have been defined:
imat
|
=
|
Mat<s32>
|
umat
|
=
|
Mat<u32>
|
fmat
|
=
|
Mat<float>
|
mat
|
=
|
Mat<double>
|
cx_fmat
|
=
|
Mat<cx_float>
|
cx_mat
|
=
|
Mat<cx_double>
|
-
In this documentation the mat type is used for convenience.
It is possible to use other types instead, e.g. fmat.
-
Functions which are wrappers for LAPACK or ATLAS functions (generally matrix decompositions) are only valid for the following types:
fmat, mat, cx_fmat, cx_mat.
-
Elements are stored with column-major ordering (i.e. column by column).
-
Constructors:
- mat()
- mat(n_rows, n_cols)
- mat(mat)
- mat(rowvec)
- mat(colvec)
- cx_mat(mat,mat) (for constructing a complex matrix out of two real matrices)
-
Advanced constructors:
- mat(aux_mem*, n_rows, n_cols, copy_aux_mem = true)
Create a matrix using data from writeable auxiliary memory.
By default the matrix allocates its own memory and copies data from the auxiliary memory (for safety).
However, if copy_aux_mem is set to false,
the matrix will instead directly use the auxiliary memory (i.e. no copying).
This is faster, but can be dangerous unless you know what you're doing!
- mat(const aux_mem*, n_rows, n_cols)
Create a matrix by copying data from read-only auxiliary memory.
-
Examples:
mat A = randu<mat>(5,5);
double x = A(1,2);
mat B = A + A;
mat C = A * B;
mat D = A % B;
B.zeros();
B.set_size(10,10);
B.zeros(10,10);
cx_mat X(A,B);
Caveat:
For mathematical correctness, scalars are treated as 1x1 matrices
during initialisation.
As such, the code below will not generate a 5x5 matrix with
every element equal to 123.0:
mat A(5,5);
A = 123.0;
Use the following code instead:
mat A(5,5);
A.fill(123.0);
Or:
mat A = 123.0 * ones<mat>(5,5);
See also:
Col<type>
colvec
vec
Caveat:
For mathematical correctness, scalars are treated as 1x1 matrices
during initialisation.
As such, the code below will not generate a column vector with
every element equal to 123.0:
colvec q(5);
q = 123.0;
Use the following code instead:
colvec q(5);
q.fill(123.0);
Or:
colvec q = 123.0 * ones<colvec>(5,1);
Row<type>
rowvec
Caveat:
For mathematical correctness, scalars are treated as 1x1 matrices
during initialisation.
As such, the code below will not generate a row vector with
every element equal to 123.0:
rowvec r(5);
r = 123.0;
Use the following code instead:
rowvec r(5);
r.fill(123.0);
Or:
rowvec r = 123.0 * ones<rowvec>(1,5);
Cube<type>
cube
cx_cube
-
Classes for cubes, also known as "3D matrices".
-
The root template cube class is Cube<type>, where type can be one of:
char, int, float, double, std::complex<double>, etc.
-
For convenience the following typedefs have been defined:
icube
|
=
|
Cube<s32>
|
ucube
|
=
|
Cube<u32>
|
fcube
|
=
|
Cube<float>
|
cube
|
=
|
Cube<double>
|
cx_fcube
|
=
|
Cube<cx_float>
|
cx_cube
|
=
|
Cube<cx_double>
|
-
In this documentation the cube type is used for convenience.
It is possible to use other types instead, e.g. fcube.
-
Cube data is stored as a set of slices (matrices) stored contiguously within memory.
Within each slice, elements are stored with column-major ordering (i.e. column by column).
-
Each slice can be interpreted as a matrix, hence functions which take Mat as input can generally also take cube slices as input.
-
Constructors:
cube()
cube(cube)
cube(n_rows, n_cols, n_slices)
cx_cube(cube, cube) (for constructing a complex cube out of two real cubes)
-
Advanced constructors:
- cube(aux_mem*, n_rows, n_cols, n_slices, copy_aux_mem = true)
Create a cube using data from writeable auxiliary memory.
By default the cube allocates its own memory and copies data from the auxiliary memory (for safety).
However, if copy_aux_mem is set to false,
the cube will instead directly use the auxiliary memory (i.e. no copying).
This is faster, but can be dangerous unless you know what you're doing!
- cube(const aux_mem*, n_rows, n_cols, n_slices)
Create a cube by copying data from read-only auxiliary memory.
-
Examples:
cube x(1,2,3);
cube y = randu<cube>(4,5,6);
mat A = y.slice(1); // extract a slice from the cube
// (each slice is a matrix)
mat B = randu<mat>(4,5);
y.slice(2) = B; // set a slice in the cube
cube q = y + y; // cube addition
cube r = y % y; // element-wise cube multiplication
Caveats
For mathematical correctness, scalars are treated as 1x1x1 cubes
during initialisation.
As such, the code below will not generate a cube with
every element equal to 123.0:
cube c(5,6,7);
c = 123.0;
Use the following code instead:
cube c(5,6,7);
c.fill(123.0);
Or:
cube c = 123.0 * ones<cube>(5,6,7);
See also:
field<object type>
-
Class for one and two dimensional fields of arbitrary objects
-
Constructors (where object type is another class, e.g. std::string, mat, colvec, rowvec, etc):
field<object type>(n_elem=0)
field<object type>(n_rows, n_cols)
field<object type>(field<object type>)
-
Examples:
// create a field of strings
field<std::string> S(3,2);
S(0,0) = "hello";
S(1,0) = "there";
// string fields can be saved as plain text files
S.save("string_field");
// create a colvec field with 3 rows and 2 columns
field<colvec> F(3,2);
// access components of the field
F(0,0) = colvec(5);
F(1,1) = randu<colvec>(6);
F(2,0).set_size(7);
// access element 1 of the colvec stored at 2,0
double x = F(2,0)(1);
// copy rows
F.row(0) = F.row(2);
// extract a row of colvecs from F
field<colvec> G = F.row(1);
// print the field to the standard output
G.print("G =");
// save the field to a binary file
G.save("colvec_field");
See also:
Member Functions & Variables
attributes
.n_rows
|
|
(number of rows)
|
.n_cols
|
|
(number of columns)
|
.n_elem
|
|
(total number of elements)
|
.n_slices
|
|
(number of slices)
|
.n_elem_slice
|
|
(number of elements per slice)
|
See also:
.copy_size(A)
.diag(k=0)
See also: diagvec()
element/object access via (), [] and .at()
-
Provide access to individual elements or objects stored in a container object
(i.e., Mat, Col, Row, Cube, field).
(n)
|
|
For colvec and rowvec, access the n-th element.
For mat, cube and field, access the n-th element/object under the assumption of a flat layout,
with column-major ordering of data (i.e. column by column).
An exception is thrown if the requested element is out of bounds.
The bounds check can be optionally disabled if the ARMA_NO_DEBUG or NDEBUG macro is defined.
|
|
|
|
[n]
|
|
As for (n), but without a bounds check.
Not recommended for use unless your code has been thoroughly debugged.
|
|
|
|
(i,j)
|
|
For mat and field classes, access the element/object stored at the i-th row and j-th column.
An exception is thrown if the requested element is out of bounds.
The bounds check can be optionally disabled if the ARMA_NO_DEBUG or NDEBUG macro is defined.
|
|
|
|
.at(i,j)
|
|
As for (i,j), but without a bounds check.
Not recommended for use unless your code has been thoroughly debugged.
|
|
|
|
|
(i,j,k)
|
|
Cube only: access the element stored at the i-th row, j-th column and k-th slice.
An exception is thrown if the requested element is out of bounds.
The bounds check can be optionally disabled if the ARMA_NO_DEBUG or NDEBUG macro is defined.
|
|
|
|
.at(i,j,k)
|
|
As for (i,j,k), but without a bounds check.
Not recommended for use unless your code has been thoroughly debugged. |
-
Examples:
mat A = randu<mat>(10,10);
A(9,9) = 123.0;
double x = A.at(9,9);
double y = A[99];
colvec p = randu<colvec>(10,1);
p(9) = 123.0;
double z = p[9];
.fill(value)
See also:
.is_finite()
-
Member function of Mat, Col, Row and Cube classes.
- Returns true if all elements of the object are finite.
- Returns false if at least one of the elements of the object is non-finite.
-
Examples:
mat A = randu<mat>(5,5);
mat B = randu<mat>(5,5);
B(1,1) = 0.0 / 0.0; // create a NaN
cout << A.is_finite() << endl;
cout << B.is_finite() << endl;
.is_square()
.is_vec()
-
Member function of the Mat class.
- Returns true if the matrix can be interpreted as a vector (either column or row vector).
- Returns false if the matrix can't be interpreted as a vector, or the matrix has no elements.
-
Examples:
mat A = randu<mat>(1,5);
mat B = randu<mat>(5,1);
mat C = randu<mat>(5,5);
cout << A.is_vec() << endl;
cout << B.is_vec() << endl;
cout << C.is_vec() << endl;
iterators (matrices & vectors)
-
STL-style iterators and associated member functions of the Mat, Col and Row classes.
-
iterator types:
mat::iterator
colvec::iterator
rowvec::iterator
|
|
random access iterators, for read/write access to elements;
the elements are ordered column by column
|
|
|
|
mat::const_iterator
colvec::const_iterator
rowvec::const_iterator
|
|
random access iterators, for read-only access to elements;
the elements are ordered column by column
|
|
|
|
mat::col_iterator
colvec::col_iterator
rowvec::col_iterator
|
|
random access iterators, for read/write access to the elements of a specific column
|
|
|
|
mat::const_col_iterator
colvec::const_col_iterator
rowvec::const_col_iterator
|
|
random access iterators, for read-only access to the elements of a specific column
|
|
|
|
mat::row_iterator
|
|
rudimentary forward iterator, for read/write access to the elements of a specific row
|
|
|
|
mat::const_row_iterator
|
|
rudimentary forward iterator, for read-only access to the elements of a specific row
|
|
|
|
colvec::row_iterator
rowvec::row_iterator
|
|
random access iterators, for read/write access to the elements of a specific row
|
|
|
|
colvec::const_row_iterator
rowvec::const_row_iterator
|
|
random access iterators, for read-only access to the elements of a specific row
|
-
Member functions:
.begin()
|
|
provide an iterator referring to the first element
|
.end()
|
|
provide an iterator referring to the past-the-end element
|
.begin_row(row_number)
|
|
provide an iterator referring to the first element of the specified row
|
.end_row(row_number)
|
|
provide an iterator referring to the past-the-end element of the specified row
|
.begin_col(column_number)
|
|
provide an iterator referring to the first element of the specified column
|
.end_col(column_number)
|
|
provide an iterator referring to the past-the-end element of the specified column
|
-
Examples:
mat X = randu<mat>(5,5);
mat::iterator a = X.begin();
mat::iterator b = X.end();
for(mat::iterator i=a; i!=b; ++i)
{
cout << *i << endl;
}
mat::col_iterator c = X.begin_col(1); // start of column 1
mat::col_iterator d = X.end_col(3); // end of column 3
for(mat::col_iterator i=c; i!=d; ++i)
{
cout << *i << endl;
(*i) = 123.0;
}
See also: iterator at cplusplus.com
iterators (cubes)
-
STL-style iterators and associated member functions of the Cube class.
-
iterator types:
cube::iterator
|
|
random access iterator, for read/write access to elements;
the elements are ordered slice by slice;
the elements within each slice are ordered column by column
|
|
|
|
cube::const_iterator
|
|
random access iterators, for read-only access to elements
|
|
|
|
cube::slice_iterator
|
|
random access iterator, for read/write access to the elements of a particular slice;
the elements are ordered column by column
|
|
|
|
cube::const_slice_iterator
|
|
random access iterators, for read-only access to the elements of a particular slice
|
-
Member functions:
.begin()
|
|
provide an iterator referring to the first element
|
.end()
|
|
provide an iterator referring to the past-the-end element
|
.begin_slice(slice_number)
|
|
provide an iterator referring to the first element of the specified slice
|
.end_slice(slice_number)
|
|
provide an iterator referring to the past-the-end element of the specified slice
|
-
Examples:
cube X = randu<cube>(2,3,4);
cube::iterator a = X.begin();
cube::iterator b = X.end();
for(cube::iterator i=a; i!=b; ++i)
{
cout << *i << endl;
}
cube::slice_iterator c = X.begin_slice(1); // start of slice 1
cube::slice_iterator d = X.end_slice(2); // end of slice 2
for(cube::slice_iterator i=c; i!=d; ++i)
{
cout << *i << endl;
(*i) = 123.0;
}
See also: iterator at cplusplus.com
.memptr()
See also:
.ones()
.ones(n_elem)
.ones(n_rows, n_cols)
.ones(n_rows, n_cols, n_slices)
See also:
operators: + - * / % == != <= >= < >
-
Overloaded operators for mat, colvec, rowvec and cube classes.
-
Meanings:
+ |
|
Addition of two objects. |
- |
|
Subtraction of one object from another or negation of an object. |
/ |
|
Element-wise division of an object by another object or a scalar. |
* |
|
Matrix multiplication of two objects. Not applicable to the cube class unless multiplying a cube by a scalar. |
% |
|
Schur product: element-wise multiplication of two objects. |
== |
|
Element-wise equality evaluation of two objects. Generates a matrix of type umat with entries that indicate whether at a 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". |
> |
|
As for ==, but the check is for "greater than". |
< |
|
As for ==, but the check is for "less than". |
-
An exception is thrown if incompatible object sizes are used.
-
If the +, - and % operators are chained, Armadillo will try to avoid
the generation of temporaries. No temporaries are
generated if all given objects are of the same type and size.
-
If the * operator is chained, Armadillo will try to find an
efficient ordering of the matrix multiplications.
-
Caveat: operators involving an equality comparison (i.e., ==, !=, >=, <=)
may not work as expected for floating point element types (i.e., float, double)
due to the necessarily limited precision of these types.
In other words, these operators are (in general) not recommended for matrices of type mat or fmat.
-
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;
// V is constructed without temporaries
mat V = A + B + A + B;
imat AA = "1 2 3; 4 5 6; 7 8 9;";
imat BB = "3 2 1; 6 5 4; 9 8 7;";
// compare elements
umat ZZ = (AA >= BB);
See also:
.print(header="")
.print(stream, header="")
See also: saving & loading matrices
.print_trans(header="")
.print_trans(stream, header="")
-
Member function of Mat, Col and Row.
-
Similar to .print(), with the difference being that a transposed version of the object is printed.
.raw_print(header="")
.raw_print(stream, header="")
.raw_print_trans(header="")
.raw_print_trans(stream, header="")
-
Member function of Mat, Col and Row.
-
Similar to .raw_print(), with the difference being that a transposed version of the object is printed.
.reset()
See also: .set_size()
.save(name, file_type = arma_binary)
.save(stream, file_type = arma_binary)
.load(name, file_type = auto_detect)
.load(stream, file_type = auto_detect)
.quiet_save(name, file_type = arma_binary)
.quiet_save(stream, file_type = arma_binary)
.quiet_load(name, file_type = auto_detect)
.quiet_load(stream, file_type = auto_detect)
- Member functions of Mat, Col, Row and Cube classes.
- Store/retrieve data in files or streams.
- On success, save(), load(), quiet_save(), and quite_load() will return a bool set to true.
- save() and quiet_save() will return a bool set to false if the saving process fails.
-
load() and quiet_load() will return a bool set to false if the loading process fails.
Additionaly, the object will be reset so it has no elements.
- load() and save() will print error messages to the standard output if any problems are encountered.
- quiet_load() and quiet_save() do not print any error messages.
-
The following file formats are supported:
auto_detect |
|
for load() and quiet_load(): try to automatically detect the file type as one of the formats described below.
This is the default operation.
|
raw_ascii |
|
Numerical data stored in raw ASCII format (no header),
with the numbers separated by whitespace.
The number of columns must be the same in each row.
Data which was saved in Matlab/Octave using the -ascii option can be read in Armadillo, except for complex numbers.
Complex numbers are stored in standard C++ notation (a tuple surrounded by brackets: e.g. (1.23,4.56) indicates 1.24 + 4.56i).
Cubes are loaded as one slice.
|
arma_ascii |
|
Numerical data stored in human readable text format, with a simple header to speed up loading.
The header indicates the type of matrix as well as the number of rows and columns.
For cubes, the header additionally specifies the number of slices.
|
arma_binary |
|
Numerical data stored in machine dependent binary format, with a simple header to speed up loading.
The header indicates the type of matrix as well as the number of rows and columns.
For cubes, the header additionally specifies the number of slices.
|
pgm_binary |
|
Image data stored in Portable Gray Map (PGM) format.
Applicable to Mat only.
Saving int, float or double matrices is a lossy operation, as each element is copied and converted to an 8 bit representation.
As such the matrix should have values in the [0,255] interval, otherwise the resulting image may not display correctly.
|
ppm_binary |
|
Image data stored in Portable Pixel Map (PPM) format.
Applicable to Cube only.
Saving int, float or double matrices is a lossy operation, as each element is copied and converted to an 8 bit representation.
As such the cube/field should have values in the [0,255] interval, otherwise the resulting image may not display correctly.
|
-
Examples:
mat A = randu<mat>(5,5);
A.save("A1.mat"); // default save format is arma_binary
A.save("A2.mat", arma_ascii);
mat B;
// automatically detect format type
B.load("A1.mat");
mat C;
// force loading in the arma_ascii format
C.load("A2.mat", arma_ascii);
// example of saving/loading using a stream
std::stringstream s;
A.save(s);
mat D;
D.load(s);
// example of testing for success
mat E;
bool status = E.load("A2.mat");
if(status == true)
{
cout << "loaded okay" << endl;
}
else
{
cout << "problem with loading" << endl;
}
See also: saving/loading fields
.save(name, file_type = arma_binary)
.save(stream, file_type = arma_binary)
.load(name, file_type = auto_detect)
.load(stream, file_type = auto_detect)
.quiet_save(name, file_type = arma_binary)
.quiet_save(stream, file_type = arma_binary)
.quiet_load(name, file_type = auto_detect)
.quiet_load(stream, file_type = auto_detect)
- Member functions of the field class.
- Store/retrieve fields in files or stream.
- On success, save(), load(), quiet_save(), and quite_load() will return a bool set to true.
- save() and quiet_save() will return a bool set to false if the saving process fails.
-
load() and quiet_load() will return a bool set to false if the loading process fails.
Additionaly, the field will be reset so it has no elements.
- load() and save() will print error messages to the standard output if any problems are encountered.
- quiet_load() and quiet_save() do not print any error messages.
-
Fields with objects of type std::string are saved and loaded as raw text files.
The text files do not have a header.
Each string is separated by a whitespace.
load() and quiet_load() will only accept text files that have the same number of strings on each line.
The strings can have variable lengths.
-
Other than storing string fields as text files, the following file formats are supported:
auto_detect |
|
-
load(): try to automatically detect the field format type as one of the formats described below.
This is the default operation.
|
arma_binary |
|
-
Objects are stored in machine dependent binary format.
-
Default type for fields of type Mat, Col or Row.
-
Only applicable to fields of type Mat, Col or Row.
|
ppm_binary |
|
-
Image data stored in Portable Pixmap Map (PPM) format.
-
Only applicable to fields of type Mat, Col or Row.
-
.load(): Loads the specified image and stores the red, green and blue components as three separate matrices.
The resulting field is comprised of the three matrices,
with the red, green and blue components in the first, second and third matrix, respectively.
-
.save(): Saves a field with exactly three matrices of equal size as an image.
It is assumed that the red, green and blue components are stored in the first, second and third matrix, respectively.
Saving int, float or double matrices is a lossy operation,
as each matrix element is copied and converted to an 8 bit representation.
|
- See also: saving/loading matrices and cubes
.set_size(n_elem) |
|
(member function of Col, Row, and field)
|
.set_size(n_rows, n_cols) |
|
(member function of Mat and field)
|
.set_size(n_rows, n_cols, n_slices) |
|
(member function of Cube)
|
See also: .reset()
submatrix views
- A collection of member functions of Mat, Col and Row classes that provide submatrix views.
.row( row_number )
.col( column_number )
.rows( first_row, last_row )
.cols( first_column, last_column )
.submat( first_row, first_column, last_row, last_column )
-
Examples:
mat A = zeros<mat>(5,10);
mat B = A.submat(0,1,2,3);
A.submat(0,1,2,3) = randu<mat>(3,3);
A.row(1) = randu<mat>(1,10);
See also: join_rows() & join_cols()
subcube views and slices
- A collection of member functions of the Cube class that provide subcube views.
.slice( slice_number )
.slices( first_slice, last_slice )
.subcube( first_row, first_column, first_slice, last_row, last_column, last_slice )
-
An individual slice can be interpreted as a matrix (i.e. an instance of the Mat class).
-
The size of individual slices can't be changed.
-
Examples:
cube A = randu<cube>(2,3,4);
mat B = A.slice(1);
A.slice(0) = randu<mat>(2,3);
A.subcube(0,0,1, 1,1,2) = randu<cube>(2,2,2);
A.slice(0)(1,2) = 99.0;
subfield views
- A collection of member functions of the field class that provide subfield views.
.row( row_number )
.col( column_number )
.rows( first_row, last_row )
.cols( first_column, last_column )
.subfield( first_row, first_column, last_row, last_column )
.swap_rows(row1, row2)
.swap_cols(col1, col2)
See also: fliplr() & flipud()
.zeros()
.zeros(n_elem)
.zeros(n_rows, n_cols)
.zeros(n_rows, n_cols, n_slices)
See also:
Other Classes
running_stat<type>
See also:
running_stat_vec<type>(calc_cov = false)
See also:
wall_clock
-
Simple wall clock timer class, for measuring the number of elapsed seconds between two intervals.
-
Examples:
wall_clock timer;
mat A = randu<mat>(4,4);
mat B = randu<mat>(4,4);
mat C;
timer.tic();
for(u32 i=0; i<100000; ++i)
C = A + B + A + B;
double n_secs = timer.toc();
cout << "took " << n_secs << " seconds" << endl;
Generated Vectors/Matrices
eye(n_rows, n_cols)
See also:
linspace(start, end, N)
-
Generate a vector with N elements;
the values of the elements linearly increase from start upto (and including) end.
-
Usage:
- vector_type v = linspace<vector_type>(start, end, N)
- matrix_type X = linspace<matrix_type>(start, end, N)
-
If a matrix_type is specified, the resultant matrix will have one column.
-
Examples:
colvec q = linspace<colvec>(10, 20, 5);
rowvec r = linspace<rowvec>(10, 20, 5);
mat X = linspace<mat>(10, 20, 5);
ones(n_elem)
ones(n_rows, n_cols)
ones(n_rows, n_cols, n_slices)
-
Generate a vector, matrix or cube with all elements set to one.
-
Usage:
- vector_type v = ones<vector_type>(n_elem)
- matrix_type X = ones<matrix_type>(n_rows, n_cols)
- cube_type X = ones<cube_type>(n_rows, n_cols, n_slices)
-
Examples:
mat A = ones<mat>(5,6);
mat B = 123.0 * ones<mat>(5,6);
cube C = 123.0 * ones<cube>(5,6,7);
See also:
randu(n_elem)
randu(n_rows, n_cols)
randu(n_rows, n_cols, n_slices)
randn(n_elem)
randn(n_rows, n_cols)
randn(n_rows, n_cols, n_slices)
-
Generate a vector, matrix or cube with the elements set to random values.
- randu() uses a uniform distribution in the [0,1] interval.
- 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)
- cube_type C = randu<cube_type>(n_rows, n_cols, n_slices)
-
Examples:
colvec q = randu<colvec>(5);
rowvec r = randu<rowvec>(5);
mat A = randu<mat>(5,6);
cube C = randu<cube>(5,6,7);
repmat(mat A, num_copies_per_row, num_copies_per_col)
toeplitz(A)
toeplitz(A,B)
See also:
zeros(n_elem)
zeros(n_rows, n_cols)
zeros(n_rows, n_cols, n_slices)
-
Generate a vector, matrix or cube with the elements set to zero.
-
Usage:
- vector_type v = zeros<vector_type>(n_elem)
- matrix_type X = zeros<matrix_type>(n_rows, n_cols)
- cube_type X = zeros<cube_type>(n_rows, n_cols, n_slices)
-
Examples:
colvec q = zeros<colvec>(5);
rowvec r = zeros<rowvec>(5);
mat A = zeros<mat>(5,6);
cube C = zeros<cube>(5,6,7);
See also:
- .zeros() (member function of Mat, Col, Row and Cube)
- .ones() (member function of Mat, Col, Row and Cube)
- ones()
Functions Individually Applied to Each Element of a Matrix/Cube
abs(mat)
abs(cube)
abs(cx_mat)
abs(cx_cube)
eps(mat)
eps(cx_mat)
eps(float)
eps(double)
eps(cx_float)
eps(cx_double)
See also:
misc functions (exp, log, log10, pow, sqrt, square, trunc_exp, trunc_log)
trigonometric functions (cos, sin, tan, ...)
Scalar Valued Functions of Vectors/Matrices/Cubes
accu(mat)
accu(cube)
-
Accumulate (sum) all elements
-
Examples:
mat A = randu<mat>(5,5);
double x = accu(A);
mat B = randu<mat>(5,5);
double y = accu(A % B);
// operator % performs element-wise multiplication,
// hence accu(A % B) is a "multiply-and-accumulate"
// operation
See also: sum()
as_scalar(expression)
See also:
det(mat)
See also:
dot(A, B)
norm_dot(A, B)
See also:
log_det(val, sign, mat)
See also:
norm(X, p)
See also:
rank(mat)
rank(cx_mat)
See also:
trace(mat)
See also:
Scalar/Vector Valued Functions of Vectors/Matrices
diagvec(mat, k=0)
See also:
min(mat, dim=0)
min(rowvec)
min(colvec)
max(mat, dim=0)
max(rowvec)
max(colvec)
-
For a matrix argument, return the minimum/maximum value for each column (dim=0), or each row (dim=1).
-
For a vector argument, return the minimum/maximum value.
-
Examples:
colvec q = randu<colvec>(10,1);
double x = max(q);
mat A = randu<mat>(10,10);
rowvec b = max(A);
// same result as max(A)
// the 0 explicitly indicates
// "traverse across rows"
rowvec c = max(A,0);
// the 1 explicitly indicates
// "traverse across columns"
colvec d = max(A,1);
// find the overall maximum value
double y = max(max(A));
prod(mat, dim=0)
prod(rowvec)
prod(colvec)
-
For a matrix argument, return the product of elements in each column (dim=0), or each row (dim=1).
-
For a vector argument, return the product of all elements.
-
Examples:
colvec q = randu<colvec>(10,1);
double x = prod(q);
mat A = randu<mat>(10,10);
rowvec b = prod(A);
// same result as prod(A)
// the 0 explicitly indicates
// "traverse across rows"
rowvec c = prod(A,0);
// the 1 explicitly indicates
// "traverse across columns"
colvec d = prod(A,1);
// find the overall product
double y = prod(prod(A));
See also: Schur product
sum(mat, dim=0)
sum(rowvec)
sum(colvec)
-
For a matrix argument, return the sum of elements in each column (dim=0), or each row (dim=1).
-
For a vector argument, return the sum of all elements.
-
To get a sum of all the elements regardless of the argument type (i.e. matrix or vector),
you may wish to use accu() instead.
-
Examples:
colvec q = randu<colvec>(10,1);
double x = sum(q);
mat A = randu<mat>(10,10);
rowvec b = sum(A);
// same result as sum(A)
// the 0 explicitly indicates
// "traverse across rows"
rowvec c = sum(A,0);
// the 1 explicitly indicates
// "traverse across columns"
colvec d = sum(A,1);
// find the overall sum
double y = sum(sum(A));
See also:
statistics: mean, median, stddev, var
See also:
Vector/Matrix/Cube Valued Functions of Vectors/Matrices/Cubes
C = conv(A, B)
See also:
conv_to<type>::from(X)
See also:
conj(cx_mat)
conj(cx_cube)
See also: htrans()
cor(mat, mat, norm_type=0)
cor(rowvec, rowvec, norm_type=0)
cor(colvec, colvec, norm_type=0)
cor(colvec, rowvec, norm_type=0)
cor(rowvec, colvec, norm_type=0)
cor(mat, norm_type=0)
cor(rowvec, norm_type=0)
cor(colvec, norm_type=0)
See also:
cov(mat, mat, norm_type=0)
cov(rowvec, rowvec, norm_type=0)
cov(colvec, colvec, norm_type=0)
cov(colvec, rowvec, norm_type=0)
cov(rowvec, colvec, norm_type=0)
cov(mat, norm_type=0)
cov(rowvec, norm_type=0)
cov(colvec, norm_type=0)
See also:
cross(A, B)
See also:
diagmat(mat)
diagmat(rowvec)
diagmat(colvec)
See also: diagvec()
find(X, k=0, s="first")
-
Return a column vector (with elements of type u32) of the indices of non-zero elements of X.
-
X is intepreted as a vector, with column-by-column ordering of the elements of X.
- Relational operators can be used instead of X, e.g. A > 0.5
- 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.
- If s="last", return at most the last k indices of the non-zero elements.
-
Examples:
mat A = randu<mat>(5,5);
mat B = randu<mat>(5,5);
uvec q1 = find(A > B);
uvec q2 = find(A > 0.5);
uvec q3 = find(A > 0.5, 3, "last");
See also: sort_index()
fliplr(mat)
flipud(mat)
See also: .swap_rows() & .swap_cols() (member functions of Mat, Col and Row classes)
htrans(cx_mat)
htrans(cx_colvec)
htrans(cx_rowvec)
See also:
imag(cx_mat)
imag(cx_cube)
real(cx_mat)
real(cx_cube)
join_rows(A,B)
join_cols(A,B)
-
join_rows:
for two input matrices A and B, append each row of B to its respective row of A, provided that A and B have the same number of rows.
-
join_cols: for two input matrices A and B, append each column of B to its respective column of A, provided that A and B 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: submatrix views
kron(mat,mat)
kron(cx_mat,cx_mat)
kron(mat,cx_mat)
kron(cx_mat,mat)
See also:
reshape(mat, n_rows, n_cols, dim=0)
reshape(cube, n_rows, n_cols, n_slices, dim=0)
See also:
shuffle(mat, dim=0)
shuffle(rowvec, dim=0)
shuffle(colvec, dim=0)
sort(mat, sort_type=0, dim=0)
sort(rowvec, sort_type=0)
sort(colvec, sort_type=0)
sort_index(colvec, sort_type=0)
sort_index(rowvec, sort_type=0)
See also: find()
trans(mat)
trans(colvec)
trans(rowvec)
See also: htrans()
Decompositions and Related Functions
R = chol(X)
chol(R, X)
See also: Cholesky decomposition in MathWorld
eig_sym(colvec eigval, mat X)
eig_sym(colvec eigval, cx_mat X)
colvec eigval = eig_sym(mat X)
colvec eigval = eig_sym(cx_mat X)
eig_sym(colvec eigval, mat eigvec, mat X)
eig_sym(colvec eigval, cx_mat eigvec, cx_mat X)
-
Eigen decomposition of symmetric/hermitian matrix X.
- The eigenvalues and corresponding eigenvectors are stored in eigval and eigvec, respectively.
-
The eigenvalues are not guaranteed to be ordered.
-
An exception is thrown if X is not square.
-
There is currently no check whether X is symmetric.
-
Examples:
mat A = randu<mat>(10,10);
mat B = trans(A)*A; // generate a symmetric matrix
vec eigval;
mat eigvec;
eig_sym(eigval, eigvec, B);
See also:
eig_gen(cx_colvec eigval, cx_mat eigvec, mat X, side='r')
eig_gen(cx_colvec eigval, cx_mat eigvec, cx_mat X, side='r')
eig_gen(cx_colvec eigval, mat l_eigvec, mat r_eigvec, mat X)
eig_gen(cx_colvec eigval, cx_mat l_eigvec, cx_mat r_eigvec, cx_mat X)
See also: eigen decomposition in MathWorld
inv(mat)
See also:
lu(mat L, mat U, mat X)
lu(mat L, mat U, mat P, mat X)
-
Lower-upper decomposition (with partial pivoting) of matrix X.
-
L is a lower-triangular matrix, U is an upper-triangular matrix and P is an optional permutation matrix.
-
The second form provides the permutation matrix P, such that P*X = L*U and X = trans(P)*L*U.
-
The second form is currently considerably slower than the first form.
-
Examples:
mat A = randu<mat>(10,10);
mat L;
mat U;
mat P;
lu(L, U, P, A);
mat B = trans(P)*L*U;
See also: LU decomposition in Wikipedia
pinv(mat A, tol = 0)
pinv(cx_mat A, tol = 0)
See also:
mat coeff = princomp(mat X)
cx_mat coeff = princomp(cx_mat X)
princomp(mat coeff, mat score, mat X)
princomp(cx_mat coeff, cx_mat score, cx_mat X)
princomp(mat coeff, mat score, colvec latent, mat X)
princomp(cx_mat coeff, cx_mat score, colvec latent, cx_mat X)
princomp(mat coeff, mat score, colvec latent, colvec tsquared, mat X)
princomp(cx_mat coeff, cx_mat score, colvec latent, cx_colvec tsquared, cx_mat X)
- Principal component analysis of matrix X.
- Each row of X is an observation and each column is a variable.
- coeff: principal component coefficients.
- score: projected data.
- latent: eigenvalues of the covariance matrix of X.
- tsquared: Hotteling's statistic for each sample.
- The computation is based on singular value decomposition (SVD).
If the SVD fails, an error message is printed and the output matrices & vectors have no elements.
-
Examples:
mat A = randu<mat>(5,4);
mat coeff;
mat score;
vec latent;
vec tsquared;
princomp(coeff, score, latent, tsquared, A);
See also:
mat coeff = princomp_cov(mat X)
cx_mat coeff = princomp_cov(cx_mat X)
princomp_cov(mat coeff, colvec latent, mat X)
princomp_cov(cx_mat coeff, colvec latent, cx_mat X)
princomp_cov(mat coeff, colvec latent, colvec explained, mat X)
princomp_cov(cx_mat coeff, colvec latent, colvec explained, cx_mat X)
- Principal component analysis of the covariance matrix of the input matrix X.
- coeff: principal component coefficients.
- latent: principal component variances.
- explained: percentage of the total variance explained by each principal component.
- The computation is based on singular value decomposition (SVD).
If the SVD fails, an error message is printed and the output matrices & vectors have no elements.
-
Examples:
mat A = randu<mat>(5,4);
mat coeff;
vec latent;
vec explained;
princomp_cov(coeff, latent, explained, A);
See also:
qr(Q,R,X)
-
Decomposition of matrix X into an orthogonal (Q) and a right triangular matrix (R), such that Q*R = X.
-
If the decomposition fails, Q and R are set to have no elements and an error message is printed.
-
Examples:
mat X = randu<mat>(5,5);
mat Q, R;
qr(Q,R,X);
See also: QR decomposition in MathWorld
solve(colvec x, mat A, colvec b)
solve(mat X, mat A, mat B)
colvec x = solve(mat A, colvec b)
mat X = solve(mat A, mat B)
- Solve a system of linear equations, i.e., A*X = B, where X is unknown.
- For a square matrix A, this function is conceptually the same as X = inv(A)*B, but is more efficient.
- Similar functionality to the "\" (left division operator) operator in Matlab/Octave, i.e., X = A \ B.
- The number of rows in A and B must be the same.
- This function will also try to provide approximate solutions to under-determined
as well as over-determined systems (where matrix A is non-square).
-
If no solution is found:
- the two argument version will output a zero length vector/matrix
- the three argument versions will set X to have no elements and output a bool set to false
-
NOTE: Old versions of the ATLAS library (e.g. 3.6) have a bug which can corrupt memory and crash your program
-- later versions of ATLAS (e.g. 3.8) should work.
Using the standard LAPACK library works without problems.
-
Examples:
mat A = randu<mat>(5,5);
vec b = randu<vec>(5);
mat B = randu<mat>(5,5);
vec x = solve(A,b);
mat X = solve(A,B);
vec x2;
bool status = solve(x2, A, b);
See also:
svd(colvec s, mat X),
svd(colvec s, cx_mat X)
colvec s = svd(mat X)
colvec s = svd(cx_mat X)
svd(mat U, colvec s, mat V, mat X)
svd(cx_mat U, colvec s, cx_mat V, cx_mat X)
-
The single and two argument versions compute the singular values of X
-
The four argument version computes the singular value decomposition of X, such that:
- X = U*diagmat(s)*trans(V), if X has real numbers
- X = U*diagmat(s)*htrans(V), if X has complex numbers
-
If the decomposition fails:
- the single argument version will output a zero length vector
- the two and four argument versions output a bool set to false
-
NOTE: Old versions of the ATLAS library (e.g. 3.6) have a bug which can corrupt memory and crash your program
-- later versions of ATLAS (e.g. 3.8) should work.
Using the standard LAPACK library works without problems.
-
Examples:
mat X = randu<mat>(5,5);
mat U;
vec s;
mat V;
bool status = svd(U,s,V,X);
See also: singular value decomposition in MathWorld
Miscellaneous
math constants (pi, e, euler, gratio, sqrt2, eps, log_min, log_max)
physical constants (speed of light, etc)
See also: physical constant entry in Wikipedia.
log_add(log_a, log_b)
-
Safe replacement for log(exp(log_a) + exp(log_b))
-
Usage:
-
scalar_type log_c = log_add(log_a, log_b)
-
scalar_type is either float or double
-
log_a, log_b and log_c must have the same type
s32, u32
-
s32 is a typedef for a 32 bit wide signed int
-
u32 is a typedef for a 32 bit wide unsigned int
- See also: C++ variable types
cx_float, cx_double
conversion table between Matlab/Octave and Armadillo syntax
Matlab/Octave
|
|
Armadillo
|
|
Notes
|
|
|
|
|
|
A(1, 1)
|
|
A(0, 0)
|
|
indexing in Armadillo starts at 0
|
A(k, k)
|
|
A(k-1, k-1)
|
|
|
|
|
|
|
|
size(A,1)
|
|
A.n_rows
|
|
read only
|
size(A,2)
|
|
A.n_cols
|
|
|
size(Q,3)
|
|
Q.n_slices
|
|
Q is a cube (3D array)
|
numel(A)
|
|
A.n_elem
|
|
|
|
|
|
|
|
A(:,k)
|
|
A.col(k-1)
|
|
|
A(k, :)
|
|
A.row(k-1)
|
|
|
A(:, p:q)
|
|
A.cols(p-1, q-1)
|
|
|
A(p:q, :)
|
|
A.rows(p-1, q-1)
|
|
|
A(p:q, r:s)
|
|
A.submat(p-1, r-1, q-1, s-1)
|
|
A.submat(first_row, first_col, last_row, last_col)
|
|
|
|
|
|
Q(:, :, k)
|
|
Q.slice(k-1)
|
|
Q is a cube (3D array)
|
Q(:, :, t:u)
|
|
Q.slices(t-1, u-1)
|
|
|
Q(p:q, r:s, t:u)
|
|
Q.subcube(p-1, r-1, t-1, q-1, s-1, u-1)
|
|
.subcube(first_row, first_column, first_slice, last_row, last_column, last_slice)
|
|
|
|
|
|
A.'
|
|
trans(A)
|
|
simple transpose
(the conjugate of each element is not taken)
|
A'
|
|
htrans(A)
|
|
Hermitian transpose
(for complex matrices, the conjugate of each element is taken)
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
C = complex(A,B)
|
|
cx_mat C = cx_mat(A,B)
|
|
|
|
|
|
|
|
A .* B
|
|
A % B
|
|
element-wise multiplication
|
A ./ B
|
|
A / B
|
|
element-wise division
|
A \ B
|
|
solve(A,B)
|
|
|
A = A + 1;
|
|
A++
|
|
|
A = A - 1;
|
|
A--
|
|
|
|
|
|
|
|
A = [ 1 2; 3 4; ]
|
|
A = "1 2; 3 4;"
|
|
|
X = [ A B ]
|
|
X = join_rows(A,B)
|
|
|
X = [ A; B ]
|
|
X = join_cols(A,B)
|
|
|
|
|
|
|
|
A
|
|
cout << A << endl;
or
A.print("A =");
|
|
|
|
|
|
|
|
save -ascii 'A.dat' A
|
|
A.save("A.dat", raw_ascii);
|
|
Matlab/Octave matrices saved as ascii are readable by Armadillo (and vice-versa)
|
load -ascii 'A.dat'
|
|
A.load("A.dat", raw_ascii);
|
|
|
|
|
|
|
|
S = { 'abc'; 'def' }
|
|
field<std::string> S(2);
S(0) = "abc";
S(1) = "def";
|
|
fields can store arbitrary objects
|
example program
-
If you save the program below as arma_prog.cpp,
under Linux you can compile it using:
g++ arma_prog.cpp -o arma_prog -O1 -larmadillo
-
You may also want to have a look at the example programs that come with the Armadillo archive.
#include <iostream>
#include <armadillo>
using namespace std;
using namespace arma;
int main(int argc, char** argv)
{
mat A = randu<mat>(4,5);
mat B = randu<mat>(4,5);
cout << "A*trans(B) =" << endl;
cout << A*trans(B) << endl;
return 0;
}
|