find(vector==value) not working

25 ビュー (過去 30 日間)
Luke Stalder
Luke Stalder 2019 年 11 月 13 日
回答済み: Ruger28 2019 年 11 月 13 日
Why does find(vector==value) not work? I am trying to find the index of a value of 0.16 in a vector defined as vector=0:0.01:0.3. find(vector==0.16) should return 17 but returns an empty vector. Why?

採用された回答

Star Strider
Star Strider 2019 年 11 月 13 日
You have encountered floating-point approximation error. See the documentation on Floating-Point Numbers for a full explanation.
Try this:
vector=0:0.01:0.3;
Result = find(vector<=0.16, 1, 'last');
producing:
Result =
17

その他の回答 (2 件)

Ruger28
Ruger28 2019 年 11 月 13 日
From the FIND documentation
To find a noninteger value, use a tolerance value based on your data. Otherwise, the result is sometimes an empty matrix due to floating-point roundoff error.
y = 0:0.1:1
y = 1×11
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 1.0000
k = find(y==0.3)
k = 1x0 empty double row vector
k = find(abs(y-0.3) < 0.001)
k = 4

Thomas Satterly
Thomas Satterly 2019 年 11 月 13 日
While it looks like the 17th value of your vector is 0.16, it's actually slightly off because of floating point precision. What you should do is find the closest value to your target value that's below an acceptable limit. For example:
vector = 0:0.01:0.3;
tolerance = eps * 2; % eps is the floating point number tolerance
target = 0.16;
match = find(abs(vector - target) <= tolerance);

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by