Logical function not returning correct value for smaller numbers

조회 수: 1 (최근 30일)
Ravi Rahul Kumar Shah
Ravi Rahul Kumar Shah 2020년 12월 23일
편집: Mischa Kim 2020년 12월 23일
I am writing a function which sould return back the index of the searched value. Because the numbers are smaller, the buildin find is not working.
Most of the times it works, but if the number is really small, it is not working. The condition Vektor(k) == x is false, although the numbers are exactly same.
function index_1 = find_Index(x,Vektor)
for k = 1:length(Vektor)
if Vektor(k) == x
index_1 = k;
return;
end
end
end

채택된 답변

Mischa Kim
Mischa Kim 2020년 12월 23일
편집: Mischa Kim 2020년 12월 23일
Hi Ravi, try something like
if abs(Vektor(k) - x) < tol
and use tol to fine-tune your algorithm depending on how "different" your numbers are, e.g.
tol = 1e-4

추가 답변 (1개)

Walter Roberson
Walter Roberson 2020년 12월 23일
function index_1 = find_Index(x, Vektor)
index_1 = [];
[found, idx] = ismembertol(x, Vektor);
if found; index_1 = idx; end
This returns empty if no match, and the index of an "almost-exact" match if found . For example if x was sqrt(13)/3*3 and Vektor contained sqrt(13) then there is not a bit-for-bit equality, but ismembertol() would be willing to overlook the 4.44089209850063e-16 difference in values.
Or perhaps you would prefer
function index_1 = find_Index(x, Vektor)
[~, index_1] = min( abs(Vektor - x) );
which returns the index of the nearest value, even if numerically it is a distance. For example, the input could be 73 and the match might be against 100

카테고리

Help CenterFile Exchange에서 Newton-Raphson Method에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by