There are many times where I have found myself searching a time vector for a specific time to offset data. Typically I use find(t == d) where d is a specific value which is known to be in t and t is a vector with length > 2000. However, for specific values of d (which I cannot understand) the boolean statement returns a zero vector (d not detected). For Example.
t = 1:1/400:10;
c = 5.465;
d = 5.565;
e = 5.665;
n = find(t == c);
m = find(t == d);
p = find(t == e);
produces n = 1787, m = null double vector, p = 1867.
and t(1827) = 5.5650

 채택된 답변

Dave B
Dave B 2021년 11월 4일
편집: Dave B 2021년 11월 4일

0 개 추천

This is a common error with floating point precision, the numbers are not actually the same:
t = 1:1/400:10;
d = 5.565;
m = find(t == d)
m = 1×0 empty double row vector
[~,nearest]=min(abs(t-d));
t(nearest) % looks the same?
ans = 5.5650
d==t(nearest) % but it isn't equal
ans = logical
0
d-t(nearest) % the values are ever so slightly different
ans = 8.8818e-16
% Here's the common workaround:
tol = 1e-10; %whatever is appropriate for your data
find(abs(t-d)<tol)
ans = 1827
Here's a wikipedia about floating point error mitigation: https://en.wikipedia.org/wiki/Floating-point_error_mitigation
Here's a nice description about floating point from Cleve: https://blogs.mathworks.com/cleve/2014/07/07/floating-point-numbers/
If you search for "floating point error", or "floating point error matlab" you'll find lots more resources.
Note that there are a few functions in MATLAB that take a tolerance, like ismembertol but there's no isequaltol

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

R2021a

태그

질문:

2021년 11월 4일

편집:

2021년 11월 4일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by