Assertion failed: (other.rows() == 1 || other.cols() == 1), function resizeLike,
file /usr/local/Cellar/eigen/3.3.7/include/eigen3/Eigen/src/Core/PlainObjectBase.h, line 374.
运行带有eigen的c++程序时遇到上述错误,有错误的代码如下,在运行时在main函数里先运行_regression_vectors函数,紧接着就运行_do_first_regression函数,但是出现了上述错误。
输出结果显示_regression_vectors函数已经运行了它的最后一个语句cout << "Y.transpose(): " << Y.transpose() << endl;并且将Y.transpose()的结果输出了,但是程序紧接着就运行_do_first_regression函数时连第一个语句cout << “start!” << endl;都没有运行,让人百思不得其解,为什么前一个函数最后一句都运行完了,而下一个函数连第一句都运行不了?而且还出现上述错误
void _regression_vectors(vector<Vector2d> points, int point_index, double H) {
//Constructs Y, X and weights for the D_l regression(直线回归)
Vector2d points_i = points[point_index];
cout << "points_i: " << points_i << endl;
int N = points.size();
cout << "N: " << N << endl;
W = MatrixXd::Zero(N, N);
C = MatrixXd::Ones(N, 2);
Y.resize(N, 1);
cout << "C.transpose(): " << C.transpose() << endl;
for (int u = 0; u < N; u++) {
Vector2d points_u = points[u];
cout << " points_" << u << ": " << points_u.transpose() << endl;
double R = (points_i - points_u).norm();
double r = R * R;
cout << "r: " << r << endl;
if (r < H) {
W(u, u) = (2 * pow(r, 3) / pow(H, 3)) - (3 * pow(r, 2) / pow(H, 2)) + 1;
}
else {
W(u, u) = 0;
}
cout << "W(u, u): " << W(u, u) << endl;
C(u, 1) = points_u(0);
Y(u ,0) = points_u(1);
}
cout << "C.transpose(): " << C.transpose() << endl;
cout << "Y.transpose(): " << Y.transpose() << endl;
}
MatrixXd _do_first_regression(MatrixXd Y, MatrixXd C, VectorXd W) {
//Performs the initial regression step
//Minimises D_l for the point specified by point point_index
//拟合直线,求出a,b
cout << "start!" << endl;
MatrixXd A = (C.transpose()) * W * C;
cout << "A: " << A << endl;
MatrixXd B = (C.transpose()) * W * Y;
cout << "B: " << B << endl;
MatrixXd X = A.jacobiSvd(ComputeThinU | ComputeThinV).solve(B);
cout << "X: " << X << endl;
return X;
}
最后通过设置断点debug发现,程序运行到MatrixXd _do_first_regression(MatrixXd Y, MatrixXd C, VectorXd W) 停止,检查发现W的类型VectorXd有问题,前面的函数中W是MatrixXd类型,但运行到_do_first_regression函数时将W设置为了VectorXd类型,从而出现了开头所示的错误
解决办法:
这个错误是错将MatrixXd类型的变量设置为VectorXd类型导致的,解决办法是将VectorXd改回MatrixXd即可,修改后的_do_first_regression函数如下
MatrixXd _do_first_regression(MatrixXd Y, MatrixXd C, MatrixXd W)