# How to compare Eigen matrices for equality

📅 2016-Feb-16 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ eigen ⬩ 📚 Archive

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

Usage:

``````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);``````