GitHub

Matrix library for C++20

A tiny C++20 general-purpose library for dense, fixed-size and dynamically-sized matrices with no dependencies.

Overview

Features:

Limitations:

Sample Code (some possible operations)

Matrix<float, 3, 3> mat{ 1,2,3,4,5,6,7,8,9 };
auto mat2 = mat * 2.f - mat;

// Take sqrt of all entries
mat.apply([](float& f) {f = std::sqrtf(f); });

// Iterate over all entries (row first)
for (const auto& el : mat) {}
// Iterate over one row
for (const auto& el : mat.row(1)) {}
// Copy one row into another
mat.row(1) = mat.row(0);
// Copy matrix block into other matrix
mat2.block(1, 1, 2, 2) = mat.block(0, 0, 2, 2);

Vector3f vec = mat.col(0);
vec.x() += 5;
float norm = vec.norm();

RowVector3f row_vec(7);
// Auto cast 1x1 matrix to scalar
float scalar = row_vec * vec; 

// Pretty print matrices
cout << mat << mat2 << vec;

// Dynamic matrices
Matrix<float, dynamic, dynamic> dyn_mat{ 3, 4 };

Documentation

Documentation overview

This library has been tested with Visual C++, Clang and GCC.

Classes

Class
Definition
class Matrix<T,m,n>
Main class for m×nmatrices of type T.
class Matrix_view<T>
Matrix view class for viewing or modifying parts of a matrix like a block, row or column.
class Matrix_iterator<T>
Random access iterator (in fact even contiguous iterator) for iterating through a contiguous array in memory (matrix data).
class Matrix_stride_iterator<T>
Random access iterator for iterating i.e. vertically through a contiguous array in memory.
class Matrix_block_iterator<T>
Bi-directional iterator for iterating through a matrix block within a bigger matrix.
struct Shape<bool>
Shape representation. For fixed-sized matrices, it takes up no space.

Type Definitions

Type
Definition
using Index = size_t
Index and size type for access in matrices.
using Vector<T,n> = Matrix<T,1,n>
Column vector partial specialization of Matrix.
using RowVector<T,m> = Matrix<T,m,1>
Row vector partial specialization of Matrix.

Predefined Matrices

Member
Definition
using Matrix2f = Matrix<float, 2, 2>
using Matrix3f = Matrix<float, 3, 3>
using Matrix4f = Matrix<float, 4, 4>
using Vector2f = Vector<float, 2>
using Vector3f = Vector<float, 3>
using Vector4f = Vector<float, 4>
using RowVector2f = RowVector<float, 2>
using RowVector3f = RowVector<float, 3>
using RowVector4f = RowVector<float, 4>
float matrix and vector types.
using Matrix2d = Matrix<double, 2, 2>
using Matrix3d = Matrix<double, 3, 3>
using Matrix4d = Matrix<double, 4, 4>
using Vector2d = Vector<double, 2>
using Vector3d = Vector<double, 3>
using Vector4d = Vector<double, 4>
using RowVector2d = RowVector<double, 2>
using RowVector3d = RowVector<double, 3>
using RowVector4d = RowVector<double, 4>
double matrix and vector types.

Exceptions

By default, exceptions are not activated. Calls to Matrix::block(Index, Index, Index, Index), Matrix::row(Index), Matrix::col(Index), Matrix_view::operator=(const Matrix_view&), Matrix_view::operator=(const Matrix&) and Matrix(const Matrix_view&) will do an assertation when running in debug mode. Defining the macro MATRIX_EXCEPTIONS before including this library will instead turn on exceptions for these cases.

Class
Definition
struct Matrix_view_mismatch
Thrown when assignment (copy of data) from one Matrix_view into another is attempted with different block dimensions.
struct Matrix_block_domain_error
Thrown when creation of a block is attempted that exceeds the dimensions of the matrix.
struct Matrix_shape_error
Thrown when attempting to perform operations on two matrices with invalid dimensions.


Matrix Class

Template Parameters

Template Parameter
Definition and notes
class T
Value type for the underlying data. T needs to be default-constructible, copy-insertable, destructable, equality-comparable and capable of basic arithmetic.
Index m
Number of rows (height of the matrix).
Index n
Number of columns (width of the matrix).

Matrix satisfies the requirements for a C++ Container, ReversableContainer and ContiguousContainer with the same exceptions as std::array that the complexity of swapping is linear and the default-constructed matrix is not empty for non-zero m and n.

Types

Member
Definition
using value_type = T
Value type for the underlying data.
using size_type = size_t
Type used for indexing and sizes.
using difference_type = ptrdiff_t
Type used for pointer differences.
using iterator = Matrix_iterator<T>,
using const_iterator = Matrix_iterator<const T>
Iterator through all elements of the matrix (row first).
using reverse_iterator = std::reverse_iterator<iterator>,
using const_reverse_iterator = std::reverse_iterator<const_iterator>
Reverse iterator.

Constructors (fixed-size)

Member
Definition
Matrix()
Default-initializes data (i.e. zero for arithmetic types).
Matrix(const T& value)
Initializes all entries to value.
Matrix(const std::initializer_list<T> elems)
Initializes matrix elements from initializer list. When too many values are provided, the last ones are discarded; when too few are provided, the rest is default-initialized.
Matrix(const std::array<T, m*n>& elems)
Copies values from a std::array with fitting length.
Matrix(std::array<T, m*n>&& elems)
Constructs a matrix by moving std::array with fitting length.
Matrix(const Matrix_view<T>& mat_view)
Constructs a matrix copying the matrix block mat_view.

Constructors (dynamically-sized)

Member
Definition
Matrix(Index m, Index n)
Default-initializes data (i.e. zero for arithmetic types).
Matrix(Index m, Index n, const T& value)
Initializes all entries to value.
Matrix(Index m, Index n, const std::initializer_list<T> elems)
Initializes matrix elements from initializer list. When too many values are provided, the last ones are discarded; when too few are provided, the rest is default-initialized.
Matrix(Index m, Index n, const std::vector<T>& elems)
Copies values from a std::vector with fitting length.
Matrix(Index m, Index n, std::vector<T>&& elems)
Constructs a matrix by moving std::vector with fitting length.
Matrix(const Matrix_view<T>& mat_view)
Constructs a matrix copying the matrix block mat_view.

Matrix Access

Member
Definition
size_type rows() const
Returns number of rows.
size_type cols() const
Returns number of columns.
size_type size() const
Returns total number of entries (rows times columns).
T* data(),
const T* data() const
Get raw pointer to data.
T& operator()(size_type i, size_type j),
const T& operator()(size_type i, size_type j) const
Get element at row i and column j.
T& at(size_type i, size_type j),
const T& at(size_type i, size_type j) const
Get element at row i and column j (bounds checked).
void fill(const T& c)
Fill each entry of matrix with value c.
void swap(Matrix& a)
Swap content of matrix with another matrix (of same dimensions).

Arithmetic

Member
Definition
template<class F>
Matrix& apply(F f)
Apply a callable to each entry of the matrix (f takes one argument: the entry).
template<class F>
Matrix& apply(F f, const T& c)
Apply a callable to each entry of the matrix (f takes two arguments: the entry and the constant c).
template<class F>
Matrix& apply(F f, const Matrix& a))
Apply a callable elementwise to two matrices (f takes two arguments: one entry of each matrix).
Matrix& operator+=(const T& c)
Matrix operator+(const T& c) const
Adds a scalar to each element of the matrix.
Matrix& operator-=(const T& c)
Matrix operator-(const T& c) const
Subtracts a scalar from each element of the matrix.
Matrix& operator*=(const T& c)
Matrix operator*(const T& c) const
Multiplies each element of the matrix with a scalar.
Matrix& operator/=(const T& c)
Matrix operator/(const T& c) const
Divides each element of the matrix by a scalar.
Matrix& operator%=(const T& c)
Matrix operator%(const T& c) const
Takes the modulo of each element of the matrix by a scalar.
Matrix& operator+=(const Matrix& a)
Matrix operator+(const Matrix& a) const
Adds another matrix.
Matrix& operator-=(const Matrix& a)
Matrix operator-(const Matrix& a) const
Subtracts another matrix.

Resize and reshape (only for dynamically-sized matrices)

Member
Definition
void resize(Index m, Index n)
Resizes the matrix to the new given dimensions. Elements of the matrix can move position since this function effectively calls resize() on the vector storing the matrix' elements.
void reshape(Index m, Index n)
Reshapes the matrix. Only possible when the total number of elements do not change.
void reshape(Shape new_shape)
Reshapes the matrix. Only possible when the total number of elements do not change.
Shape shape() const
Returns the shape of the matrix.

Other Matrix Operations

Member
Definition
Matrix<T, n, m> transpose() const
Returns the transposed matrix.
Matrix<T, m, p> operator*(const Matrix<T, n, p>& a) const
Returns the matrix product of two matrices.
template<class U>
Matrix<U, m, n> cast() const
Cast matrix to value type U. This function returns a new matrix. The type U needs to fulfill std::convertible_to<T, U>.

Iterators

Member
Definition
iterator begin(),
const_iterator begin() const
Returns an iterator to the first element.
iterator end(),
const_iterator end() const
Returns an iterator to the last element.
reverse_iterator rbegin(),
const_reverse_iterator rbegin() const
Returns a reverse iterator to the beginning.
reverse_iterator rend(),
const_reverse_iterator rend() const
Returns a reverse iterator to the end.

Row/Column/Block Access

The programmer is responsible to ensure that a Matrix_view<T> does not outlive the pointed-to matrix.

Member
Definition
Matrix_view<T> block(size_type row, size_type col, size_type rows, size_type cols),
Matrix_view<const T> block(size_type row, size_type col, size_type rows, size_type cols) const
Returns a Matrix_view<T> referencing a rectangular block of the matrix.
Matrix_view<T> row(size_type row),
Matrix_view<const T> row(size_type row) const
Returns a Matrix_view<T> referencing the specified row of the matrix.
Matrix_view<T> col(size_type col),
Matrix_view<const T> col(size_type col) const
Returns a Matrix_view<T> referencing the specified column of the matrix.

Vector-specific Operations

Matrices that have at least one dimension equal 1 are considered vectors. These feature some additional operations.

Member
Definition
T& operator[](size_type i),
const T& operator[](size_type i) const
Access the i'th element of the vector.
T& x(size_type i),
const T& x(size_type i) const
Access the first element of the vector (only for vectors with 1 to 3 elements).
T& y(size_type i),
const T& y(size_type i) const
Access the second element of the vector (only for vectors with 2 to 3 elements).
T& z(size_type i),
const T& z(size_type i) const
Access the third element of the vector (only for vectors with exactly 3 elements).
T norm() const
Returns the euclidian length (L2-norm) of the vector.
Matrix& normalize()
Normalizes the vector to length 1 by dividing by its norm.
T operator*(const Matrix& vec)
Returns the inner (scalar) product of two vectors. Note, that this differs from the matrix product defined above in that it is only defined for vectors with equal dimensions while the latter can only be performed on Matrices two m×n and n×p. The matrix product operation for vectors is therefore only valid for one row and one column vector, respectively.
operator T() const
Cast option for 1×1 matrices to the scalar value type.

Factory Functions

Static Member
Definition
static Matrix zero()
Returns a matrix filled with zeros.
static Matrix zero(Index m, Index n)
(dynamic version). Returns a matrix filled with zeros.
static Matrix identity()
Returns an identity matrix (operation only defined for square matrices).
static Matrix identity(Index n)
(dynamic version). Returns an identity matrix (operation only defined for square matrices).


Matrix_view Class

Types

Member
Definition
using value_type = T
Value type for the underlying data.
using pointer = T*
Value type for the underlying data.
using reference = T&
Value type for the underlying data.
using size_type = size_t
Type used for indexing and sizes.
using iterator = Matrix_block_iterator<T>,
using const_iterator = Matrix_block_iterator<const T>
Iterator through all elements of the block (row first).
using reverse_iterator = std::reverse_iterator<iterator>,
using const_reverse_iterator = std::reverse_iterator<const_iterator>
Reverse iterator.

Constructors

Member
Definition
Matrix_view()
Default constructor.
Matrix_view(T* ptr, size_type m, size_type n, size_type rows, size_type cols)
Initializes Matrix view with dimensions to pointed-to matrix and dimensions of block.

Iterators

Member
Definition
iterator begin(),
const_iterator begin() const
Returns an iterator to the beginning.
iterator end(),
const_iterator end() const
Returns an iterator to the end.
reverse_iterator rbegin(),
const_reverse_iterator rbegin() const
Returns a reverse iterator to the beginning.
reverse_iterator rend(),
const_reverse_iterator rend() const
Returns a reverse iterator to the end.

Member functions

Member
Definition
size_type rows() const
Number of rows the block view has.
size_type cols() const
Number of columns the block view has.
Matrix_view& operator=(const Matrix_view& mat_view)
Copies the content of the matrix block that mat_view points to the matrix block that this view points to. The block dimensions need to match.
template<size_type m, size_type n>
Matrix_view& operator=(const Matrix<T, m, n>& mat)
Copies the content of mat into the matrix block that this view points to. Block dimensions and dimensions of mat need to match.


Global Functions

Function
Definition
template<class T, Index m, Index n>
bool operator==(const Matrix<T, m, n>& a, const Matrix<T, m, n>& b)
Returns true if the matrices are equal.
template<class T, Index m, Index n>
bool operator!=(const Matrix<T, m, n>& a, const Matrix<T, m, n>& b)
Returns false if the matrices are equal.
template<class T, Index m, Index n>
Matrix<T, m, n>& operator-(const Matrix<T, m, n>& mat)
Unary minus operator (has the same effect as calling mat*-1).
template<class T, Index m, Index n>
Matrix<T, m, n>& operator*(const T& c, const Matrix<T, m, n>& mat)
Multiplies the matrices with a scalar from the left (has the same effect as calling mat*c).
template<class T, Index m>
T distance(const Vector& a, const Vector& b)
template<class T, Index m>
T distance(const RowVector& a, const RowVector& b)
Returns the distance, treating both vectors as points in euclidian space (has the same effect as calling (a - b).norm()).
template<class T, Index n>
Matrix<T, n, n> diag(const T(&values)[n])
Returns a diagonal matrix filled with the elements in values. All other values are default-initialized. Template parameters can be deduced automatically
template<class T, Index n>
Matrix<T, n, n> antidiag(const T(&values)[n])
Returns an antidiagonal matrix filled with the elements in values. All other values are default-initialized. Template parameters can be deduced automatically