Jansen du Plessis
Jansen du Plessis

Reputation: 235

Can't access elements of an eigen linear system solution

I'm just started of using eigen but for some strange reason I'm struggling with something that should be simple. The code below is a simplified version of some similar computation I would like to perform (Solve x in Ax = b).

Input:

auto N = 10;
auto A = Matrix<Float, Dynamic, Dynamic>::Identity(N, N);
auto b = Matrix<Float, Dynamic, 1>::Constant(N, 1, 1);
std::cout << "A: " << std::endl
          << A << std::endl
          << "b: " << std::endl 
          << b << std::endl;
auto x = A.fullPivLu().solve(b);
std::cout << "x(" << x.rows() << ", " << x.cols()
          << "): " << std::endl << x << std::endl;

Output:

A: 
1 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1
b: 
1
1
1
1
1
1
1
1
1
1
x(10, 1): 
mouse: /home/jansen/devel/build/external/eigen/include/eigen3/Eigen/src/Core/Block.h:119: Eigen::Block<Eigen::Matrix<double, -1, -1, 0, -1, -1>, 1, -1, false>::Block(XprType &, Index) [XprType = Eigen::Matrix<double, -1, -1, 0, -1, -1>, BlockRows = 1, BlockCols = -1, InnerPanel = false]: Assertion `(i>=0) && ( ((BlockRows==1) && (BlockCols==XprType::ColsAtCompileTime) && i<xpr.rows()) ||((BlockRows==XprType::RowsAtCompileTime) && (BlockCols==1) && i<xpr.cols()))' failed.
[1]    21192 abort (core dumped)  ./src/mouse

A and b is well formed and the solution x even have the right dimensions but whenever I try to access an element of x I get an assertion failure. From the assertion I deduce that some sort of out of bounds error happens but I can't figure out why?

Upvotes: 0

Views: 178

Answers (1)

ggael
ggael

Reputation: 29225

Please don't abuse of auto with expression template libraries, see this page. Typically, in your case, x is not a Matrix<> object but an abstract object saying that A\b as to be computed... The solution is thus:

Matrix<Float, Dynamic, 1> x = A.fullPivLu().solve(b);

Upvotes: 3

Related Questions