Why does MATLAB not finding a element from my matrix?

x = 0.4:0.01:0.5
x = 1x11
0.4000 0.4100 0.4200 0.4300 0.4400 0.4500 0.4600 0.4700 0.4800 0.4900 0.5000
idx = find(x==0.41)
idx = 1x0 empty double row vector

3 件のコメント

Dyuman Joshi
Dyuman Joshi 2024 年 3 月 27 日
Welcome to the world of floating point numbers! Here not all numbers can be represented exactly in binary form.
Stephen has provided an extensive list of material which you can refer to - for detailed information and explainations regarding the same.
Also, see - ismembertol.
Tshikaya
Tshikaya 2024 年 3 月 27 日
Thank you for the tip. My problem was actually the following:
A = zeros(1,100);
x = zeros(1,100);
for i = 1:100
x(i) = 0.01*randi([38 45],1,1);
if ismember(0.41,x(i));
A(i) = 10;
else
A(i) = -1;
end
end
So I was shoked to see that x was sometimes 0.41 but still not picking from the code. I have just changed ismember by ismembertol and now everything is fine.
Walter Roberson
Walter Roberson 2025 年 6 月 24 日
Note that the colon operator is handled as repeated addition, so 0.4, 0.4+0.1, 0.4+0.1+0.1, 0.4+0.1+0.1+0.1 and so on. Because double precision numbers operate in binary instead of in decimal, 0.1 cannot be exactly represented, and instead each 0.1 addition adds 0.1000000000000000055511151231257827021181583404541015625
Mathworks could have chosen an impletation of (initial value) + increment * (position in the sequence minus 1), so 0.4 + [0, 1, 2, 3, 4 ...] * 0.1 ... but Mathworks did not chose that (possibly for efficiency reasons.)

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

 採用された回答

Stephen23
Stephen23 2024 年 3 月 27 日
移動済み: Dyuman Joshi 2024 年 3 月 27 日

1 投票

Testing for exact equivalence of binary floating point numbers should be avoided.
Compare the values, are they actually the same? (hint: no):
x = 0.4:0.01:0.5;
fprintf('%.40f\n', x(2), 0.41)
0.4100000000000000310862446895043831318617 0.4099999999999999755750934582465561106801
The recommended approach is to compare the absolute difference against a tolerance:
tol = 1e-5;
abs(x(2)-0.41)<tol
ans = logical
1
More information on this topic:
This is worth reading as well:

2 件のコメント

Tshikaya
Tshikaya 2024 年 3 月 27 日
Thank you for your answer
Steven Lord
Steven Lord 2025 年 6 月 24 日
If you're using release R2024b or later, you could use the isapprox function to determine if two numbers are approximately equal.

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

その他の回答 (0 件)

カテゴリ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by