class mrpt::math::CMatrixB

This class is a “CSerializable” wrapper for “CMatrixBool”.

For a complete introduction to Matrices and vectors in MRPT, see: https://www.mrpt.org/Matrices_vectors_arrays_and_Linear_Algebra_MRPT_and_Eigen_classes

#include <mrpt/math/CMatrixB.h>

class CMatrixB:
    public mrpt::serialization::CSerializable,
    public mrpt::math::CMatrixDynamic
{
public:
    // typedefs

    typedef T value_type;

    // construction

    CMatrixB(size_t row = 1, size_t col = 1);
    CMatrixB(const CMatrixBool& m);

    //
methods

    T det() const;
    CMatrixDynamic<T> inverse() const;
    CMatrixDynamic<T> inverse_LLt() const;
    int rank(T threshold = 0) const;
    bool chol(CMatrixDynamic<T>& U) const;
    bool eig(CMatrixDynamic<T>& eVecs, std::vector<T>& eVals, bool sorted = true) const;
    bool eig_symmetric(CMatrixDynamic<T>& eVecs, std::vector<T>& eVals, bool sorted = true) const;
    T maximumDiagonal() const;
    T minimumDiagonal() const;
    T trace() const;
    void unsafeRemoveColumns(const std::vector<std::size_t>& idxs);
    void removeColumns(const std::vector<std::size_t>& idxsToRemove);
    void unsafeRemoveRows(const std::vector<std::size_t>& idxs);
    void removeRows(const std::vector<std::size_t>& idxsToRemove);
    void insertMatrix(const int row_start, const int col_start, const OTHERMATVEC& submat);
    void insertMatrixTransposed(const int row_start, const int col_start, const OTHERMATVEC& submat);
    CMatrixFixed<T, BLOCK_ROWS, BLOCK_COLS> blockCopy(int start_row = 0, int start_col = 0) const;
    CMatrixDynamic<T> blockCopy(int start_row, int start_col, int BLOCK_ROWS, int BLOCK_COLS) const;
    void matProductOf_AAt(const MAT_A& A);
    void matProductOf_AtA(const MAT_A& A);
    void fill(const T& val);
    auto block(int start_row, int start_col);
    T minCoeff() const;
    T maxCoeff() const;
    bool isSquare() const;
    bool empty() const;
    T norm_inf() const;
    T norm() const;
    T dot(const CVectorDynamic<T>& v) const;
    void matProductOf_Ab(const CMatrixDynamic<T>& A, const CVectorDynamic<T>& b);
    void matProductOf_Atb(const CMatrixDynamic<T>& A, const CVectorDynamic<T>& b);
    T sum() const;
    T sum_abs() const;
    std::string asString() const;
    bool fromMatlabStringFormat(const std::string& s, mrpt::optional_ref<std::ostream> dump_errors_here = std::nullopt);
    std::string inMatlabFormat(const std::size_t decimal_digits = 6) const;

    void saveToTextFile(
        const std::string& file,
        mrpt::math::TMatrixTextFileFormat fileFormat = mrpt::math::MATRIX_FORMAT_ENG,
        bool appendMRPTHeader = false,
        const std::string& userHeader = std::string()
        ) const;

    void loadFromTextFile(std::istream& f);
    void loadFromTextFile(const std::string& file);
    CMatrixB& operator = (const CMatrixBool& m);
    void swap(CMatrixDynamic<T>& o);
    size_type rows() const;
    size_type cols() const;
    matrix_size_t size() const;
    void setSize(size_t row, size_t col, bool zeroNewElements = false);
    void resize(size_t vectorLen);
    void resize(const matrix_size_t& siz, bool zeroNewElements = false);
    const T* data() const;
    T* data();
    T& operator () (size_t row, size_t col);
    const T& operator () (size_t row, size_t col) const;
    T& operator [] (size_t ith);
    const T& operator [] (size_t ith) const;

    template <typename VECTOR>
    void appendRow(const VECTOR& in);

    template <typename VECTOR>
    void appendCol(const VECTOR& in);

    template <typename VECTOR>
    void asVector(VECTOR& out) const;

    template <
        typename EIGEN_MATRIX = eigen_t,
        typename EIGEN_MAP = Eigen::Map<EIGEN_MATRIX, MRPT_MAX_ALIGN_BYTES, Eigen::InnerStride<1>>
        >
    EIGEN_MAP asEigen();

    template <
        typename EIGEN_MATRIX = eigen_t,
        typename EIGEN_MAP = Eigen::Map<const EIGEN_MATRIX, MRPT_MAX_ALIGN_BYTES, Eigen::InnerStride<1>>
        >
    EIGEN_MAP asEigen() const;

    CVectorDynamic<Scalar> llt_solve(const CVectorDynamic<Scalar>& b) const;
    CVectorDynamic<Scalar> lu_solve(const CVectorDynamic<Scalar>& b) const;
    void setDiagonal(const std::size_t N, const T value);
    void setDiagonal(const T value);
    void setDiagonal(const std::vector<T>& diags);
    void matProductOf_AB(const CMatrixDynamic<T>& A, const CMatrixDynamic<T>& B);
};

Inherited Members

public:
    //
methods

    void setConstant(const Scalar value);
    void setConstant(size_t nrows, size_t ncols, const Scalar value);
    void setConstant(size_t nrows, const Scalar value);
    void assign(const std::size_t N, const Scalar value);
    void setZero();
    void setZero(size_t nrows, size_t ncols);
    void setZero(size_t nrows);
    static Derived Constant(const Scalar value);
    static Derived Constant(size_t nrows, size_t ncols, const Scalar value);
    static Derived Zero();
    static Derived Zero(size_t nrows, size_t ncols);
    auto block(int start_row, int start_col, int BLOCK_ROWS, int BLOCK_COLS);
    auto block(int start_row, int start_col, int BLOCK_ROWS, int BLOCK_COLS) const;
    auto transpose();
    auto transpose() const;
    auto array();
    auto array() const;
    auto operator - () const;

    template <typename S2, class D2>
    auto operator + (const MatrixVectorBase<S2, D2>& m2) const;

    template <typename S2, class D2>
    void operator += (const MatrixVectorBase<S2, D2>& m2);

    template <typename S2, class D2>
    auto operator - (const MatrixVectorBase<S2, D2>& m2) const;

    template <typename S2, class D2>
    void operator -= (const MatrixVectorBase<S2, D2>& m2);

    template <typename S2, class D2>
    auto operator * (const MatrixVectorBase<S2, D2>& m2) const;

    auto operator * (const Scalar s) const;

    template <int N>
    CMatrixFixed<Scalar, N, 1> tail() const;

    template <int N>
    CMatrixFixed<Scalar, N, 1> head() const;

    Scalar& coeffRef(int r, int c);
    const Scalar& coeff(int r, int c) const;
    Scalar minCoeff(std::size_t& outIndexOfMin) const;
    Scalar minCoeff(std::size_t& rowIdx, std::size_t& colIdx) const;
    Scalar maxCoeff(std::size_t& outIndexOfMax) const;
    Scalar maxCoeff(std::size_t& rowIdx, std::size_t& colIdx) const;
    void operator += (Scalar s);
    void operator -= (Scalar s);
    void operator *= (Scalar s);
    CMatrixDynamic<Scalar> operator * (const CMatrixDynamic<Scalar>& v);
    Derived operator + (const Derived& m2) const;
    void operator += (const Derived& m2);
    Derived operator - (const Derived& m2) const;
    void operator -= (const Derived& m2);
    Derived operator * (const Derived& m2) const;
    Scalar dot(const MatrixVectorBase<Scalar, Derived>& v) const;

    template <typename OTHERMATVEC>
    bool operator == (const OTHERMATVEC& o) const;

    template <typename OTHERMATVEC>
    bool operator != (const OTHERMATVEC& o) const;

    Derived& mvbDerived();
    const Derived& mvbDerived() const;
    auto col(int colIdx);
    auto col(int colIdx) const;
    auto row(int rowIdx);
    auto row(int rowIdx) const;

    template <typename VECTOR_LIKE>
    void extractRow(int rowIdx, VECTOR_LIKE& v) const;

    template <typename VECTOR_LIKE>
    VECTOR_LIKE extractRow(int rowIdx) const;

    template <typename VECTOR_LIKE>
    void extractColumn(int colIdx, VECTOR_LIKE& v) const;

    template <typename VECTOR_LIKE>
    VECTOR_LIKE extractColumn(int colIdx) const;

    template <int BLOCK_ROWS, int BLOCK_COLS>
    CMatrixFixed<Scalar, BLOCK_ROWS, BLOCK_COLS> extractMatrix(
        const int start_row = 0,
        const int start_col = 0
        ) const;

    CMatrixDynamic<Scalar> extractMatrix(
        const int BLOCK_ROWS,
        const int BLOCK_COLS,
        const int start_row,
        const int start_col
        ) const;

    Derived& mbDerived();
    const Derived& mbDerived() const;
    void setIdentity();
    void setIdentity(const std::size_t N);
    static Derived Identity();
    static Derived Identity(const std::size_t N);
    CMatrixDynamic& operator = (const CMatrixDynamic<T>& m);

    template <typename U>
    CMatrixDynamic& operator = (const CMatrixDynamic<U>& m);

    template <class Derived>
    CMatrixDynamic& operator = (const Eigen::MatrixBase<Derived>& m);

    template <std::size_t ROWS, std::size_t COLS>
    CMatrixDynamic& operator = (const CMatrixFixed<T, ROWS, COLS>& m);

    template <typename V, size_t N>
    CMatrixDynamic& operator = (V(&) theArray [N]);

    CMatrixDynamic& operator = (CMatrixDynamic&& m);

Typedefs

typedef T value_type

The type of the matrix elements.

Construction

CMatrixB(size_t row = 1, size_t col = 1)

Constructor.

CMatrixB(const CMatrixBool& m)

Copy constructor.

Methods

T det() const

Determinant of matrix.

CMatrixDynamic<T> inverse() const

Returns the inverse of a general matrix using LU.

CMatrixDynamic<T> inverse_LLt() const

Returns the inverse of a symmetric matrix using LLt.

int rank(T threshold = 0) const

Finds the rank of the matrix via LU decomposition.

Uses Eigen’s default threshold unless threshold>0.

bool chol(CMatrixDynamic<T>& U) const

Cholesky M=U T * U decomposition for symmetric matrix (upper-half of the matrix is actually ignored.

Returns:

false if Cholesky fails

bool eig(CMatrixDynamic<T>& eVecs, std::vector<T>& eVals, bool sorted = true) const

Computes the eigenvectors and eigenvalues for a square, general matrix.

Use eig_symmetric() for symmetric matrices for better accuracy and performance. Eigenvectors are the columns of the returned matrix, and their order matches that of returned eigenvalues.

Parameters:

sorted

If true, eigenvalues (and eigenvectors) will be sorted in ascending order.

eVecs

The container where eigenvectors will be stored.

eVals

The container where eigenvalues will be stored.

Returns:

false if eigenvalues could not be determined.

bool eig_symmetric(CMatrixDynamic<T>& eVecs, std::vector<T>& eVals, bool sorted = true) const

Read: eig()

This only uses the lower-triangular part of the matrix

(Since MRPT 2.5.2) If sorted==true, the smallest eigenvalue is checked to be non-negative, and resetted to zero if found to be negative due to rounding errors in the internal Eigen3 routines.

T maximumDiagonal() const

Returns the maximum value in the diagonal.

T minimumDiagonal() const

Returns the minimum value in the diagonal.

T trace() const

Returns the trace of the matrix (not necessarily square).

void unsafeRemoveColumns(const std::vector<std::size_t>& idxs)

Removes columns of the matrix.

This “unsafe” version assumes indices sorted in ascending order.

void removeColumns(const std::vector<std::size_t>& idxsToRemove)

Removes columns of the matrix.

Indices may be unsorted and duplicated

void unsafeRemoveRows(const std::vector<std::size_t>& idxs)

Removes rows of the matrix.

This “unsafe” version assumes indices sorted in ascending order.

void removeRows(const std::vector<std::size_t>& idxsToRemove)

Removes rows of the matrix.

Indices may be unsorted and duplicated

void insertMatrix(
    const int row_start,
    const int col_start,
    const OTHERMATVEC& submat
    )

Copies the given input submatrix/vector into this matrix/vector, starting at the given top-left coordinates.

void insertMatrixTransposed(
    const int row_start,
    const int col_start,
    const OTHERMATVEC& submat
    )

Like insertMatrix(), but inserts submat ` (transposed)

CMatrixFixed<T, BLOCK_ROWS, BLOCK_COLS> blockCopy(int start_row = 0, int start_col = 0) const

const blockCopy() : Returns a copy of the given block

CMatrixDynamic<T> blockCopy(int start_row, int start_col, int BLOCK_ROWS, int BLOCK_COLS) const

const blockCopy() : Returns a copy of the given block (non templated version, dynamic sizes)

void matProductOf_AAt(const MAT_A& A)

this = A * A T

void matProductOf_AtA(const MAT_A& A)

this = A T * A

void fill(const T& val)

Fill all the elements with a given value (Note: named “fillAll” since “fill” will be used by child classes)

auto block(int start_row, int start_col)

non-const block() : Returns an Eigen::Block reference to the block

T minCoeff() const

Minimum value in the matrix/vector.

T maxCoeff() const

Maximum value in the matrix/vector.

bool isSquare() const

returns true if matrix is NxN

bool empty() const

returns true if matrix/vector has size=0

T norm_inf() const

Compute the norm-infinite of a vector (

\[||\mathbf{v}||_\infnty\]

), ie the maximum absolute value of the elements.

T norm() const

Compute the L2 norm of a vector/array/matrix (the Euclidean distance to the origin, taking all the elements as a single vector).

See also:

norm

T dot(const CVectorDynamic<T>& v) const

dot product of this \cdot v

void matProductOf_Ab(const CMatrixDynamic<T>& A, const CVectorDynamic<T>& b)

this = A * b , with A and b a dynamic matrix & vector

void matProductOf_Atb(const CMatrixDynamic<T>& A, const CVectorDynamic<T>& b)

this = A T * b , with A and b a dynamic matrix & vector

T sum() const

Sum of all elements in matrix/vector.

T sum_abs() const

Sum of the absolute value of all elements in matrix/vector.

std::string asString() const

Returns a string representation of the vector/matrix, using Eigen’s default settings.

bool fromMatlabStringFormat(
    const std::string& s,
    mrpt::optional_ref<std::ostream> dump_errors_here = std::nullopt
    )

Reads a matrix from a string in Matlab-like format, for example: “[1 0 2; 0 4 -1]” The string must start with ‘[’ and end with ‘]’.

Rows are separated by semicolons ‘;’ and columns in each row by one or more whitespaces ‘ ‘ or tabs ‘’. Commas ‘,’ between elements are NOT allowed.

This format is also used for CConfigFile::read_matrix.

Returns:

true on success. false if the string is malformed, and then the matrix will be resized to 0x0.

See also:

inMatlabFormat, CConfigFile::read_matrix

std::string inMatlabFormat(const std::size_t decimal_digits = 6) const

Exports the matrix as a string compatible with Matlab/Octave.

See also:

fromMatlabStringFormat()

void saveToTextFile(
    const std::string& file,
    mrpt::math::TMatrixTextFileFormat fileFormat = mrpt::math::MATRIX_FORMAT_ENG,
    bool appendMRPTHeader = false,
    const std::string& userHeader = std::string()
    ) const

Saves the vector/matrix to a file compatible with MATLAB/Octave text format.

Parameters:

file

The target filename.

fileFormat

See TMatrixTextFileFormat. The format of the numbers in the text file.

appendMRPTHeader

Insert this header to the file “% File generated by MRPT. Load with MATLAB with: VAR=load(FILENAME);”

userHeader

Additional text to be written at the head of the file. Typically MALAB comments “% This file blah blah”. Final end-of-line is not needed.

See also:

loadFromTextFile, CMatrixDynamic::inMatlabFormat, SAVE_MATRIX

void loadFromTextFile(std::istream& f)

Loads a vector/matrix from a text file, compatible with MATLAB text format.

Lines starting with ‘’ or ‘#’ are interpreted as comments and ignored.

Parameters:

std::runtime_error

On format error.

See also:

saveToTextFile, fromMatlabStringFormat

void loadFromTextFile(const std::string& file)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

CMatrixB& operator = (const CMatrixBool& m)

Assignment operator for float matrixes.

void swap(CMatrixDynamic<T>& o)

Swap with another matrix very efficiently (just swaps a pointer and two integer values).

size_type rows() const

Number of rows in the matrix.

See also:

rows()

size_type cols() const

Number of columns in the matrix.

See also:

rows()

matrix_size_t size() const

Get a 2-vector with [NROWS NCOLS] (as in MATLAB command size(x))

void setSize(size_t row, size_t col, bool zeroNewElements = false)

Changes the size of matrix, maintaining the previous contents.

void resize(size_t vectorLen)

Resizes as a Nx1 vector.

void resize(const matrix_size_t& siz, bool zeroNewElements = false)

Resize the matrix.

const T* data() const

Return raw pointer to row-major data buffer.

All matrix cells can be assumed to be stored contiguously in memory, i.e. row stride = column count.

T* data()

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

T& operator () (size_t row, size_t col)

Subscript operator to get/set individual elements.

const T& operator () (size_t row, size_t col) const

Subscript operator to get individual elements.

T& operator [] (size_t ith)

Subscript operator to get/set an individual element from a row or column matrix.

Parameters:

std::exception

If the object is not a column or row matrix.

const T& operator [] (size_t ith) const

Subscript operator to get/set an individual element from a row or column matrix.

For non-vectors (NxM matrices), it returns the i-th matrix element, in RowMajor order.

Parameters:

std::exception

If the object is not a column or row matrix.

template <typename VECTOR>
void appendRow(const VECTOR& in)

Appends a new row to the MxN matrix from a 1xN vector.

The lenght of the vector must match the width of the matrix, unless it’s empty: in that case the matrix is resized to 1xN.

CMatrixDouble  M(0,0);
CVectorDouble  v(7),w(7);
// ...
M.appendRow(v);
M.appendRow(w);

Parameters:

std::exception

On incorrect vector length.

See also:

extractRow

appendCol

template <typename VECTOR>
void appendCol(const VECTOR& in)

Appends a new column to the matrix from a vector.

The length of the vector must match the number of rows of the matrix, unless it is (0,0).

Parameters:

std::exception

On size mismatch.

See also:

extractCol

appendRow

template <typename VECTOR>
void asVector(VECTOR& out) const

Returns a vector containing the matrix’s values.

template <
    typename EIGEN_MATRIX = eigen_t,
    typename EIGEN_MAP = Eigen::Map<EIGEN_MATRIX, MRPT_MAX_ALIGN_BYTES, Eigen::InnerStride<1>>
    >
EIGEN_MAP asEigen()

Get as an Eigen-compatible Eigen::Map object.

template <
    typename EIGEN_MATRIX = eigen_t,
    typename EIGEN_MAP = Eigen::Map<const EIGEN_MATRIX, MRPT_MAX_ALIGN_BYTES, Eigen::InnerStride<1>>
    >
EIGEN_MAP asEigen() const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

CVectorDynamic<Scalar> llt_solve(const CVectorDynamic<Scalar>& b) const

Solves the linear system Ax=b, returns x, with A this symmetric matrix.

See also:

lu_solve()

CVectorDynamic<Scalar> lu_solve(const CVectorDynamic<Scalar>& b) const

Solves the linear system Ax=b, returns x, with A this asymmetric matrix.

See also:

llt_solve()

void setDiagonal(const std::size_t N, const T value)

Resize to NxN, set all entries to zero, except the main diagonal which is set to value

void setDiagonal(const T value)

Set all entries to zero, except the main diagonal which is set to value

void setDiagonal(const std::vector<T>& diags)

Resizes to NxN, with N the length of the input vector, set all entries to zero, except the main diagonal which is set to values in the vector.

void matProductOf_AB(const CMatrixDynamic<T>& A, const CMatrixDynamic<T>& B)

this = A*B, with A & B of the same type of this.

For products of different matrix types, use the regular * operator (which requires the <Eigen/Dense> header)