Matlab equivalent for numpy allclose?
Asked Answered
A

1

6

Numpy's allclose Returns True if two arrays are element-wise equal within a tolerance.

Is there any equivalent in Matlab?

Arleenarlen answered 10/3, 2015 at 23:16 Comment(0)
P
6

Not that I know of. But its description

If the following equation is element-wise True, then allclose returns True.

absolute(a - b) <= (atol + rtol * absolute(b))

is very easy to mimic in Matlab:

all( abs(a(:)-b(:)) <= atol+rtol*abs(b(:)) )

where a and b are the arrays (same shape, arbitrary number of dimensions), atol is absolute tolerance and rtol is relative tolerance.

If you also want to specifically check that the shapes are the same:

isequal(size(a), size(b)) && all( abs(a(:)-b(:)) <= atol+rtol*abs(b(:)) )

Note: you should not be using NumPy's default rtol and atol, by their own admission. Refer to ongoing discussion .

Porfirioporgy answered 10/3, 2015 at 23:25 Comment(2)
In the last two releases of MATLAB you can do all(...,'all'), avoids the need of (:) indexing.Knockout
I hope the note is fine. I'll repeat here with more detail just in case: you should not be using NumPy's default rtol and atol, by their own admission. Refer to ongoing discussion (latest comments are most relevant); current consensus is on rtol=1e-9 for double precision, and atol=0 is better but won't work for data containing zeros, in which case I recommend atol=1e-15 for data on order of 1 (mean(abs(x)) ~= 1).Tailpiece

© 2022 - 2024 — McMap. All rights reserved.