フィルターのクリア

Finding array index for a given array element does not work all the time

3 ビュー (過去 30 日間)
Hello,
I've been using the find(ismemeber()) function to find the index of an array element, however it does not work all the time for some reason. As you can see from the picture, it returns and empty vector at some given search values. As it can be seen from the array, it should return 393 for the last line of code. I am using the latest installation of matlab at the time of writting (2023b update 7).
To me this looks like a bug with the ismemeber() function, as it returns a false for the second entry(0.3920) but not the first entry(0.3910), se last two lines of code below. However, it could just be that i am doing something wrong? As I construct the array with a start, end, and stepsize, it shouldn't be a round of error?
Best regards Anders
mf = 0:0.001:0.6;
find(ismember(mf,0.3910))
ans = 392
find(ismember(mf,0.3920))
ans = 1×0 empty double row vector
any(ismember(mf,0.3910))
ans = logical
1
any(ismember(mf,0.3920))
ans = logical
0
  1 件のコメント
Stephen23
Stephen23 2024 年 3 月 1 日
"To me this looks like a bug with the ismemeber() function"
Nope.
"However, it could just be that i am doing something wrong?"
Yes. You are performing different operations on some binary floating point numbers and are then incorrectly assuming that these will produce exactly the same values. However that is not the case.
This is a completely expected result with binary floating point numbers:
This is worth reading as well:

サインインしてコメントする。

採用された回答

Dyuman Joshi
Dyuman Joshi 2024 年 3 月 1 日
Welcome to the world of floating point numbers, where not all numbers can be represented exactly in binary form.
When comparing floating point numbers, the best practice is to use a tolerance -
mf = 0:0.001:0.6;
val = 0.3910;
tol = 1e-6;
idx1 = find(abs(mf - val) < tol)
idx1 = 392
You can also use ismembertol here -
out = ismembertol(mf,val);
idx2 = find(out)
idx2 = 392
  1 件のコメント
Anders Tagmose Lundsfryd
Anders Tagmose Lundsfryd 2024 年 3 月 1 日
Thanks for the respons, guess it was a round of error then :D

サインインしてコメントする。

その他の回答 (1 件)

Chunru
Chunru 2024 年 3 月 1 日
Mind the round off error in searching double array
mf = 0:0.001:0.6;
i = find(abs(mf - 0.3910) < 1e-6)
i = 392

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by