A simple "bug" in finding an element in an array using find()?

Hi, I am not sure if it is a bug in matlab, but when I just simply try to find an element in an array:
list=-1:0.1:1;
find(list=0.1)
I get an strange result which is Empty matrix: 1-by-0. Instead, if I try find(list=0.6), I get the correct result 17.
Anyone have any idea?

1 件のコメント

Stephen23
Stephen23 2017 年 9 月 11 日
"I am not sure if it is a bug in matlab..."
So even after millions of person-hours testing and using MATLAB, you thought that you are the first to notice this behavior, so you did not even bother to do a simple internet search, or search this forum....
"I get an strange result"
Nope, that result looks quite normal to me.
"Anyone have any idea?"
Learn about floating-point numbers.

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

 採用された回答

Star Strider
Star Strider 2017 年 9 月 11 日

0 投票

Welcome to floating-point approximation error, and the way the colon operator works.
Try this:
list=-1:0.1:1;
find(list<=0.1,1,'last')

2 件のコメント

xk l
xk l 2017 年 9 月 11 日
Thank you for the quick answer! It solved my problem.
Star Strider
Star Strider 2017 年 9 月 11 日
As always, my pleasure!

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

その他の回答 (1 件)

James Tursa
James Tursa 2017 年 9 月 11 日

0 投票

Not a bug. Just the way floating point arithmetic works. E.g., 0.1 cannot be represented exactly in IEEE double precision, so the way the colon operator builds that list doesn't yield exactly the same number as just typing in 0.1 directly.

カテゴリ

質問済み:

2017 年 9 月 11 日

コメント済み:

2017 年 9 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by