0
votes

I have some problems with the Eigen library. When I try t access the matrices in the second for loop, I get the

eigen assertion index = 0 && index size() failed

error though I am calling the resize function of the Matrix.

Eigen::Matrix<float, 1, 2> linearRegression(Eigen::Vector2f *p, int pointCount)
{
    Eigen::MatrixXf M;
    Eigen::Matrix<float, 1, 2> A;
    Eigen::MatrixXf Y;

    M.resize(pointCount, 2);
    Y.resize(pointCount, 1);

    for (int i = 0; i < pointCount; i++)
    {
        M(i, 0) = p[i].x();
        M(i, 1) = 1;
        Y(i, 0) = p[i].y();
    }

    A = (M.transpose() * M).inverse() * M.transpose() * Y;
    return A;
}

I can see the members m_rows and m_cols of matrix M in the visual studio debugger and i does not exceed them. The error occurs directly at i = 0.

MatrixXf should be the same as Matrix<float, Dynamic, Dynamic>.

When I declare a constant pointCount and use fixed size matrices, everything works fine.

Eigen::Matrix<float, 1, 2> linearRegression(Eigen::Vector2f *p, int pointCount)
{
    const int pointCount = 30;
    ...
    Eigen::Matrix<float, pointCount, 2> M;
    Eigen::Matrix<float, 1, 2> A;
    Eigen::Matrix<float, pointCount, 1> Y;
    ...
}

What am I doing wrong?

1
probably ur matrix A is the cause? did you print out rows() and cols() accessing? try to initialize the matrices with the right dimension, and not resizing after construction.jonas_toth
use std::vector as argument to your function, or gsl::span, not related to eigen tough :)jonas_toth

1 Answers

2
votes

Your expression (M.transpose() * M).inverse() * M.transpose() * Y results in a matrix with 2 rows and 1 column, while A has 1 row and 2 columns. Because A is a fixed size, the resizing doesn't happen upon assignment. To fix, add a transpose to your expression: ((M.transpose() * M).inverse() * M.transpose() * Y).transpose()