Reputation: 75
I have a question what the best way is to care about assertion fail in Eigen C++. I know if there were wrong matrix calculation, Eigen stops program by assertion fail. For example,
MatrixXf a(2, 2);
MatrixXf b(1, 1);
MatrixXf c = a + b;
In this case, the size of matrix a and b is difference, so assertion fails occurs. Then what is the best way to avoid it ?
I can avoid, if I checked matrix size at every time before calculating.
MatrixXf a(2, 2);
MatrixXf b(1, 1);
MatrixXf c;
if (a.cols() == b.cols() && a.rows() == b.rows()) {
c = a + b;
}
But I think it's not smart way, checking each calculation.
Is there any better way to check it ? Could I catch exception by using try-catch ? Or does Eigen have any check function ?
Upvotes: 2
Views: 1189
Reputation: 18817
You can predefine the eigen_assert
macro to throw an exception instead of asserting. E.g.:
#define eigen_assert(X) do { if(!(X)) throw std::runtime_error(#X); } while(false);
// make sure Eigen is not included before your define:
#include <Eigen/Core>
But as @n.m. pointed out, you should rather fix your logic error, i.e., you should not try to add matrices if you are not sure that their sizes match.
Upvotes: 3