How to compare Eigen matrices for equality

You might want to compare two Eigen matrices for equality while writing unit tests for your mathematical operations. You could always do an element-wise comparison manually. However, there are Eigen methods that can ease the comparison.

isApprox

This method performs element-wise subtraction of the two matrices and computes the Frobenius norm of the resulting matrix. It checks if this value is less than or equal to a precision parameter that you can pass in. If you do not pass in any precision value, then the norm is compared to zero. More details on this are here

typedef typename Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> EigenMatrix;
EigenMatrix a, b;
// True if equal
bool r = a.isApprox(b);

norm

You could do the above computation yourself. For example:

typedef typename Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> EigenMatrix;
EigenMatrix a, b;
// Compare
bool r = ((a - b).norm() == 0);
// Approx compare
bool r = ((a - b).norm() < small_positive_value);

Originally posted by the following link:

How to compare Eigen matrices for equality

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s