class mrpt::math::CMatrixB

Overview

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 std::shared_ptr<mrpt::math ::CMatrixB> Ptr;
    typedef std::shared_ptr<const mrpt::math ::CMatrixB> ConstPtr;
    typedef std::unique_ptr<mrpt::math ::CMatrixB> UniquePtr;
    typedef std::unique_ptr<const mrpt::math ::CMatrixB> ConstUniquePtr;
    typedef T value_type;

    // fields

    static constexpr const char* className = "mrpt::math" "::" "CMatrixB";

    // construction

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

    // methods

    static constexpr auto getClassName();
    static const mrpt::rtti::TRuntimeClassId& GetRuntimeClassIdStatic();
    static std::shared_ptr<CObject> CreateObject();

    template <typename... Args>
    static Ptr Create(Args&&... args);

    template <typename Alloc, typename... Args>
    static Ptr CreateAlloc(
        const Alloc& alloc,
        Args&&... args
        );

    template <typename... Args>
    static UniquePtr CreateUnique(Args&&... args);

    virtual const mrpt::rtti::TRuntimeClassId* GetRuntimeClass() const;
    virtual mrpt::rtti::CObject* clone() const;
    void fill(const Scalar& val);
    T det() const;
    CMatrixDynamic<T> inverse() const;
    CMatrixDynamic<T> inverse_LLt() const;
    matrix_dim_t 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 Index_t row_start, const Index_t col_start, const OtherMatrixOrVector& submat);
    void insertMatrixTransposed(const Index_t row_start, const Index_t col_start, const OtherMatrixOrVector& submat);
    CMatrixFixed<T, BLOCK_ROWS, BLOCK_COLS> blockCopy(Index_t start_row = 0, Index_t start_col = 0) const;
    CMatrixDynamic<T> blockCopy(Index_t start_row, Index_t start_col, size_type_t BLOCK_ROWS, size_type_t BLOCK_COLS) const;
    void matProductOf_AAt(const MAT_A& A);
    void matProductOf_AtA(const MAT_A& A);

    template <matrix_dim_t BLOCK_ROWS, matrix_dim_t BLOCK_COLS>
    auto block(
        matrix_index_t start_row,
        matrix_index_t start_col
        );

    Scalar minCoeff() const;
    Scalar maxCoeff() const;
    bool isSquare() const;
    bool empty() const;
    Scalar norm_inf() const;
    Scalar norm() const;
    Scalar dot(const CVectorDynamic<Scalar>& v) const;
    void matProductOf_Ab(const CMatrixDynamic<Scalar>& A, const CVectorDynamic<Scalar>& b);
    void matProductOf_Atb(const CMatrixDynamic<Scalar>& A, const CVectorDynamic<Scalar>& b);
    Scalar sum() const;
    Scalar 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_type row, size_type col, bool zeroNewElements = false);
    void resize(size_type vectorLen);
    void resize(const matrix_size_t& siz, bool zeroNewElements = false);
    const T* data() const;
    T* data();
    T& operator () (Index row, Index col);
    const T& operator () (Index row, Index col) const;
    T& operator [] (Index ith);
    const T& operator [] (Index 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();

    CVectorDynamic<Scalar> llt_solve(const CVectorDynamic<Scalar>& b) const;
    CVectorDynamic<Scalar> lu_solve(const CVectorDynamic<Scalar>& b) const;
    void setDiagonal(const size_type_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:
    // typedefs

    typedef std::shared_ptr<CObject> Ptr;
    typedef std::shared_ptr<const CObject> ConstPtr;
    typedef std::shared_ptr<CSerializable> Ptr;
    typedef std::shared_ptr<const CSerializable> ConstPtr;
    typedef matrix_index_t Index_t;
    typedef matrix_dim_t size_type_t;

    // methods

    static const mrpt::rtti::TRuntimeClassId& GetRuntimeClassIdStatic();
    virtual const mrpt::rtti::TRuntimeClassId* GetRuntimeClass() const;
    virtual const mrpt::rtti::TRuntimeClassId* GetRuntimeClass() const;
    static const mrpt::rtti::TRuntimeClassId& GetRuntimeClassIdStatic();
    void setConstant(const Scalar value);
    void setConstant(matrix_dim_t nrows, matrix_dim_t ncols, const Scalar value);
    void setConstant(matrix_dim_t nrows, const Scalar value);
    void assign(const matrix_dim_t N, const Scalar value);
    void setZero();
    void setZero(matrix_dim_t nrows, matrix_dim_t ncols);
    void setZero(matrix_dim_t nrows);
    static Derived Constant(const Scalar value);
    static Derived Constant(matrix_dim_t nrows, matrix_dim_t ncols, const Scalar value);
    static Derived Zero();
    static Derived Zero(matrix_dim_t nrows, matrix_dim_t ncols);
    auto block(matrix_index_t start_row, matrix_index_t start_col, matrix_dim_t BLOCK_ROWS, matrix_dim_t BLOCK_COLS);
    auto block(matrix_index_t start_row, matrix_index_t start_col, matrix_dim_t BLOCK_ROWS, matrix_dim_t 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 <matrix_dim_t N>
    CMatrixFixed<Scalar, N, 1> tail() const;

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

    Scalar& coeffRef(matrix_index_t r, matrix_index_t c);
    const Scalar& coeff(matrix_index_t r, matrix_index_t c) const;
    Scalar minCoeff(matrix_index_t& outIndexOfMin) const;
    Scalar minCoeff(matrix_index_t& rowIdx, matrix_index_t& colIdx) const;
    Scalar maxCoeff(matrix_index_t& outIndexOfMax) const;
    Scalar maxCoeff(matrix_index_t& rowIdx, matrix_index_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(Index_t colIdx);
    auto col(Index_t colIdx) const;
    auto row(Index_t rowIdx);
    auto row(Index_t rowIdx) const;

    template <typename VectorLike>
    void extractRow(Index_t rowIdx, VectorLike& v) const;

    template <typename VectorLike>
    VectorLike extractRow(Index_t rowIdx) const;

    template <typename VectorLike>
    void extractColumn(Index_t colIdx, VectorLike& v) const;

    template <typename VectorLike>
    VectorLike extractColumn(Index_t colIdx) const;

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

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

    Derived& mbDerived();
    const Derived& mbDerived() const;
    void setIdentity();
    void setIdentity(const size_type_t N);
    static Derived Identity();
    static Derived Identity(const size_type_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 <size_type ROWS, size_type 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 std::shared_ptr<mrpt::math ::CMatrixB> Ptr

A type for the associated smart pointer.

typedef T value_type

The type of the matrix elements.

Construction

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

Constructor.

CMatrixB(const CMatrixBool& m)

Copy constructor.

Methods

virtual const mrpt::rtti::TRuntimeClassId* GetRuntimeClass() const

Returns information about the class of an object in runtime.

virtual mrpt::rtti::CObject* clone() const

Returns a deep copy (clone) of the object, indepently of its class.

void fill(const Scalar& val)

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

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.

matrix_dim_t 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 Index_t row_start,
    const Index_t col_start,
    const OtherMatrixOrVector& submat
    )

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

void insertMatrixTransposed(
    const Index_t row_start,
    const Index_t col_start,
    const OtherMatrixOrVector& submat
    )

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

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

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

CMatrixDynamic<T> blockCopy(Index_t start_row, Index_t start_col, size_type_t BLOCK_ROWS, size_type_t 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

template <matrix_dim_t BLOCK_ROWS, matrix_dim_t BLOCK_COLS>
auto block(
    matrix_index_t start_row,
    matrix_index_t start_col
    )

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

Scalar minCoeff() const

Minimum value in the matrix/vector.

Scalar 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

Scalar norm_inf() const

Compute the norm-infinite of a vector (.

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

), ie the maximum absolute value of the elements.

Scalar 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

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

dot product of this \cdot v

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

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

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

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

Scalar sum() const

Sum of all elements in matrix/vector.

Scalar 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 ‘t’. 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_type row, size_type col, bool zeroNewElements = false)

Changes the size of matrix, maintaining the previous contents.

void resize(size_type 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 () (Index row, Index col)

Subscript operator to get/set individual elements.

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

Subscript operator to get individual elements.

T& operator [] (Index 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 [] (Index 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 length 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

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 size_type_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)