Borrar filtros
Borrar filtros

Why does MATLAB not finding a element from my matrix?

2 visualizaciones (últimos 30 días)
Golden TSH
Golden TSH el 27 de Mzo. de 2024
Comentada: Golden TSH el 27 de Mzo. de 2024
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
  2 comentarios
Dyuman Joshi
Dyuman Joshi el 27 de Mzo. de 2024
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.
Golden TSH
Golden TSH el 27 de Mzo. de 2024
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;
A(i) = -1;
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.

Iniciar sesión para comentar.

Respuesta aceptada

Stephen23 el 27 de Mzo. de 2024
Movida: Dyuman Joshi el 27 de Mzo. de 2024
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;
ans = logical
More information on this topic:
This is worth reading as well:

Más respuestas (0)


Más información sobre Logical en Help Center y File Exchange.


Community Treasure Hunt

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

Start Hunting!

Translated by