How can I compare numbers for equality within a tolerance in MATLAB 8.0 (R2012b)?
615 views (last 30 days)
I need to compare two numeric matrices. A built-in function such as EQ (==) finds two numbers to be different even they differ by only 1e-15. Therefore, I was looking for another built-in function that could take a tolerance as an input argument, and return “true” when the absolute difference is below the tolerance threshold. How can I do that in MATLAB?
The ability to compare numeric values to within a tolerance is not available as a built-in function in MATLAB 8.0 (R2012b). As a workaround to avoid issues resulting from roundoff error, you can compare the absolute difference of the operands to a tolerance. Instead of:
you can use the following:
abs(A-B) < 1e4*eps(min(abs(A),abs(B)))
There are also a couple of entries for this on the MATLAB Central file exchange. These files are not produced by or supported by MathWorks, so any questions should be directed to the authors, however other customers have found these to be useful.
A similar approach is used by the attached file (see below), which also has a provision for handling NaN values.