Jon
Jon

Reputation: 2123

Maintaining ColXpr to a MatrixXf across conservativeResize

I am trying to maintain a variable that references the first column of an Eigen::MatrixXf across a conservative resize.

The ColXpr c looks like it is invalidated when MatrixXf m is resized and cannot be reassigned. I can see how this could protect me from mistakes but I don't understand what I should do so that c gives me the first column of the new m?

#include <iostream>
#include <Eigen/Dense>

int main()
{
    Eigen::MatrixXf m = Eigen::MatrixXf::Random(4,2);
    Eigen::MatrixXf::ColXpr c = m.col(0);

    std::cout << m << std::endl;
    //   0.680375  0.823295
    //  -0.211234 -0.604897
    //   0.566198 -0.329554
    //    0.59688  0.536459
    std::cout << c << std::endl;
    //   0.680375
    //  -0.211234
    //   0.566198
    //    0.59688

    m.conservativeResize(3, Eigen::NoChange);

    std::cout << m << std::endl;
    //   0.680375  0.823295
    //  -0.211234 -0.604897
    //   0.566198 -0.329554
    std::cout << c << std::endl;
    //  1.4013e-45
    //           0
    //  1.4013e-45
    //           0


    c = m.col(0); // <<<<< This cores with the Eigen Warning
    // Assertion `rows() == other.rows() && cols() == other.cols()' failed.

    std::cout << c << std::endl;
    return EXIT_SUCCESS;
} 

Upvotes: 0

Views: 367

Answers (1)

Sneftel
Sneftel

Reputation: 41474

Eigen expression types like ColXpr are intended to be used as temporaries, constructed and destroyed in a single line. Their main purpose is to avoid unnecessary copying -- in the ColXpr case, by aliasing data from the original array.

The aliasing is an implementation detail, NOT a user-facing feature. You shouldn't rely on ColXpr being updated even if you just modify the original matrix, let alone resize it.

If you want something that will give you the first column of the matrix, all the time, that thing is m.col(0). You can wrap that in a function if you like.

Upvotes: 1

Related Questions