# 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

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

## One thought on “How to compare Eigen matrices for equality”

1. jimmy says:

Above “norm” comparison is invalid.

isApprox essientiall uses:

|a-b|./ min(|a|,|b|) < small_positive_value

while your norm in the 1D case equates to:

sqrt( (a-b)^2 ) = |a-b| < small_positive_value.

My conclusion is that you dont know how to compare floating point values so stop misinforming others…dd

Like

This site uses Akismet to reduce spam. Learn how your comment data is processed.