Search code examples
c++matrixeigen

C++ EIGEN: How to create triangular matrix map from a vector?


I would like to use data stored into an Eigen (https://eigen.tuxfamily.org) vector

Eigen::Vector<double, 6> vec({1,2,3,4,5,6});

as if they were a triangular matrix

1 2 3
0 4 5
0 0 6

I know how to do it for a full matrix using Eigen's Map

Eigen::Vector<double, 9>  vec({1,2,3,4,5,6,7,8,9});
std::cout << Eigen::Map<Eigen::Matrix<double, 3, 3, RowMajor>>(vec.data());

which produces

1 2 3
4 5 6
7 8 9

However I do not know how to make a Map to a triangular matrix.

Is it possible? Thanks!

[Edited for clarity]


Solution

  • In my opinion this cannot be done using Map only: The implementation of Map as it is relies on stride sizes that remain constant no matter their index positions, see https://eigen.tuxfamily.org/dox/classEigen_1_1Stride.html. To implement a triangular matrix map you would have to have a Map that changes its inner stride depending on the actual column number. The interfaces in Eigen do not allow that at the moment, see https://eigen.tuxfamily.org/dox/Map_8h_source.html.


    But if you are just concerned about the extra memory you can just use Eigen's sparse matrix representation:

    https://eigen.tuxfamily.org/dox/group__TutorialSparse.html

    (Refer to section "Filling a sparse matrix".)